Node.js如何_.each内部回调同步

时间:2013-06-10 02:02:26

标签: node.js asynchronous underscore.js each

我是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

3 个答案:

答案 0 :(得分:2)

您可以使用async模块。

async.each

您的代码应如下所示:

async.each(User.friends, function(friend, cb) {
  var req = {
    url: 'https://graph.facebook.com/me/mutualfriends/'+friend.id+
      '?access_token='+User.accessToken,
    json: true
  };
  request.get(req, function(err,response,body) {
    if(err) { console.log(err); cb(true); return; }
    console.log("common friends",body.data);
    // each function call has to finish by calling `cb`
    cb(false);
  });
},
function(err) {
  if(err) return;
  console.log('Final callback');
  callback(); // here is your final callback
}
);

答案 1 :(得分:1)

试试这个。

function (callback) { //get common friends  
 var completeCount = 0;  
  _.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);
        }

        completeCount++;

        // complete count check           
        if( completeCount === User.friends.length ){
           callback()
        }
    });

  }, this);    
},

答案 2 :(得分:1)

您的代码接近正确。您必须传递并使用回调函数,否则Async不知道何时调用最终回调。

async.each(User.friends, function(friend, cb) {
    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);
            cb(null);
        } else {
            console.log(error);
            callback(error);
        }
    });
}, function(err) {
    console.log('Final callback', err);
    callback();
});