【发布时间】:2016-06-15 17:00:58
【问题描述】:
我正在实现一个用 Node.js 编写的项目并从 Mysql 获取值。 随着我在项目中的深入,我的嵌套回调就像这样
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');
}
})
}
});
}
});
}
});
我得到“回调不是函数”。我研究并发现了“回调地狱”,所以我找到了替代方案并使用 Async.js
现在我的问题是如何将此代码转换为 async.waterfall ??? 有人可以帮我弄这个吗????拜托了。
更新 1
我已经实现了 Peteb 的答案,但是,当我执行它时,只执行第一个函数。这是新代码。
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
});
【问题讨论】:
标签: javascript node.js asynchronous callback bluebird