node.js - 迭代器函数内完成的所有任务的 Node 、异步和回调

标签 node.js mongodb asynchronous

因此,我在 async.map 集合中执行任务,迭代器函数在对异步任务收集的所有数据执行任务之前执行多个异步任务。

一个快速的伪示例如下所示:

var accts=//array of accounts fechted from mongodb
async.map(accts,function(acct,callback){
   var likes=0;
   http.get(acct.facebook,function(err,resp){/*add fan count to likes*/});
   http.get(acct.twitter,function(err,resp){/*add followers to likes*/});
   //mongoose Model named artist
   artist.update({_id:acct._id},{fans:likes},function(err,acctsUpdate){});
}

我的困惑在于,更新 mongodb 可能会在两个异步任务完成之前发生,因此会破坏我的应用程序。我该如何去做呢?

最佳答案

我使用 async.waterfall 和 async.map 做了类似的事情。希望这有帮助

async.waterfall([

  function(callback){
    request.get('/api/fancy/', function(err, r, body) {
      if (err) return callback(err);
      callback(null, data);
    });

  },

  function(accts, callback){
    async.map(accts, _insertAcct, function(err, results){
      if (err) return done(err);
      done(null, results);
    });


    function _insertAcct(acct, _cb){
      if (!acct)
        return _cb(new Error('No acct data'));

      // save the acct to the db, using mongoskin
      db.collection('acct').save(audit, {upsert: true}, function(err, result){;
        if (err) return _cb(err);
        _cb(null, result)
      });
    }

  }
], function(err, results){
  // 
});

关于node.js - 迭代器函数内完成的所有任务的 Node 、异步和回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392915/

相关文章:

node.js - Express js 使用 mongodb 中的值到查询之外

mongodb - mongodb - map 减少和查找

node.js - NodeJS : Async/Await Raspberry Pi

linux - 如何让我的程序在保持响应的同时长时间休眠?

Node.js fs.watchFile 持久监视机制?

javascript - nodejs require 不是 js 文件的函数

javascript - 使用 M :N 续写创建/发布

javascript - 我无法在 Google SpreadSheets 中插入值(使用 nodejs 和模块 googleapis)

c# - 如何使用 C# 和 MongoDB 'AND' 多个 $elemMatch 子句?

javascript - 作用域和异步 JavaScript