我对 node.js 还很陌生,我不知道如何控制程序流,以便我的函数等待带有内部回调的 Underscore _.each() 块。我真的很想避免令人发指的回调炖菜。该块位于已由 nimble 的 .series([]) 控制的链中
function (callback) { //get common friends
_.each(User.friends, function (friend) { //I NEED THE FLOW TO WAIT TIL THIS COLLECTION HAS ITERATED AND ALL THE CALLBACKS ARE COMPLETE
request.get({
url: 'https://graph.facebook.com/me/mutualfriends/' + friend.id + '?access_token=' + User.accessToken,
json: true
}, function (error, response, body) { //NEED TO WAIT TIL THESE ARE ALL COMPLETED
if (!error && response.statusCode == 200) {
console.log("common friends", body.data);
} else {
console.log(error);
}
});
}, this);
callback(); //Nimble's serialization callback fires immediately
},
我在下面尝试了使用 async.each 的建议,但我无法触发迭代完成回调,以告诉 nimble 的 .series 函数继续到下一个块。
async.each(User.friends, function(friend) {
request.get({
url: 'https://graph.facebook.com/me/mutualfriends/'+friend.id+'?access_token=' + User.accessToken,
json: true
}, function (error, response, body) { //NEED TO WAIT TIL THESE ARE ALL COMPLETED
if (!error && response.statusCode == 200) {
console.log("common friends",body.data);
} else {
console.log(error);
}
});
},function(err) {console.log('Final callback');callback();}); //THIS CALLBACK DOESN'T FIRE - NIMBLE JUST SITS AND WAITS