本地callback函数Async.waterfall

我正在实施一个用Node.js编写的项目,并从Mysql获取值。 当我在我的项目更深入我的嵌套callback像这样

hold.getEntry(function(data){ var ref = data.ref; var id = data.id; var message = data.mess; var json = JSON.parse(message); if(ref === null){ } else { hold.checkPositionCandidate(ref, id, json, function(dataa){ console.log("checker " + dataa); if(dataa == false){ } else { //\/ here I get error callback is not a function hold.getVoterCount(id, json, function(votercount){ if(votercount.count == 0){ } else { checkVoter(ref, votercount.count, function(isallcorrect){ if(isallcorrect == false){ console.log('mali votes'); } else { console.log('tama votes'); } }) } }); } }); } }); 

我得到“callback不是一个函数”。 我已经研究和发现了“callback地狱”,所以我find了一个替代scheme,并使用Async.js

现在我的问题是我将如何将此代码转换为async.waterfall ??? 有人可以帮我弄这个吗???? pleaseeee。

更新1

我已经实现了Peteb的答案,但是,当我执行onlu执行第一个函数。 这是新的代码。

 var id = ""; var json = ""; async.waterfall([ function (callback) { // hold.checkPositionCandidate // if err return callback(err, null) // if successful return callback(null, dataa) hold.getEntry(function(data){ var ref = data.ref; id = data.id; var message = data.mess; json = JSON.parse(message); callback({'ref':ref, 'id':id, 'json':json}); console.log(data); }); }, function (dataa, callback) { // hold.getVoterCount // if err return callback(err, null) // if successful return callback(null, votercount) if(dataa.ref === null){ callback(null); }else{ hold.checkPositionCandidate(dataa.ref, dataa.id, dataa.json, function(dataaa){ callback(dataaa); }); } console.log('gfh'); }, function(anoData, callback) { // checkVoter // if err return callback(err, null) // if successful return callback() if(anoData === false){ } else { hold.getVoterCount(id, json, function(votercount){ if(votercount == 0){ } else { console.log('last function'); } }); } } ], function (err, results) { // When finished execute this }); 

async.waterfall你的嵌套callback,并使用一个错误优先callback函数将结果从一个函数传递到下一个函数。 所以你的callback链中的每一步都会按照他们需要执行的顺序来表示你的瀑布函数。

 async.waterfall([ function (callback) { // hold.checkPositionCandidate // if err return callback(err, null) // if successful return callback(null, dataa) }), function (dataa, callback) { // hold.getVoterCount // if err return callback(err, null) // if successful return callback(null, votercount) }), function(votercount, callback) { // checkVoter // if err return callback(err, null) // if successful return callback() }) ], function (err, results) { // When finished execute this }); 

编辑:更新的答案解决更新的问题。

callback({'ref':ref, 'id':id, 'json':json}); // this is wrong

async.waterfall()期望您的callback的第一个参数为Errornull 。 任何需要传递的值都在Error参数之后。

 // this is correct return callback(null, { ref: ref, id: id, json: json }); // this is also correct return callback(null, ref, id, json); 

示例hold.getEntry()

 hold.getEntry(function(data){ var ref = data.ref; id = data.id; var message = data.mess; json = JSON.parse(message); return callback(null, {ref: ref, id: id, json: json}); });