【问题标题】:mongoose exec call with async.parallelmongoose exec 调用与 async.parallel
【发布时间】:2015-04-19 11:22:43
【问题描述】:

我的快速控制器中有这样的代码

   function (req, res) {
      var queries = [];

      data.forEach(function (item) {
        var query = myModel.findOneAndUpdate({remoteId: item.id}, item, {upsert: true}).exec;

        queries.push(query);
      });

      async.parallel(queries, function (err, docs) {
        res.json(docs);
      });
    });

如果数据数组有 3 个项目,那么我有一个包含 3 个空值的数组。

async.parallel 函数接受带有回调参数的函数,应调用该函数以正确完成其执行。所以mongoose.Query.exec does 一样。但结果我收到了一个空对象数组。

如果我像这样包装我的exec 电话

var query = function (cb) {
  tournamentsModel.findOneAndUpdate({remoteId: item.id}, item, {upsert: true}).exec(function (err, model) {
    cb(err, model);
  });
};
queries.push(query);

一切正常,结果我从 mongo 收到了 3 个文档。 当exec 方法执行相同操作时,为什么我应该显式调用传递给async.parallel 函数调用的回调?

【问题讨论】:

    标签: node.js asynchronous parallel-processing mongoose


    【解决方案1】:

    当您直接将查询的 exec 函数作为要执行的函数传递给 async.parallel 时,您将丢失包含要运行的查询的该函数调用的 this 上下文。

    要使用这种方法,您需要调用 bind 以返回一个新函数,该函数将调用 exec 并带有正确的 this 上下文;所以是这样的:

    var query = Query.prototype.exec.bind(
        myModel.findOneAndUpdate({remoteId: item.id}, item, {upsert: true})
    );
    queries.push(query);
    

    自己调用exec 可能更简洁,但将async 回调传递给它:

    var query = function(cb) {
        myModel.findOneAndUpdate({remoteId: item.id}, item, {upsert: true}).exec(cb);
    }
    queries.push(query);
    

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2017-05-03
      • 2013-01-20
      • 1970-01-01
      • 2018-12-29
      • 2016-05-28
      • 2015-10-11
      • 1970-01-01
      相关资源
      最近更新 更多