如何在继续之前等待 findOneAndUpdate 完成 async.series

How to wait for findOneAndUpdate to finish before continuing async.series

我有一个种子文件设置来填充我的 mongodb。我正在设置一个计数器,这样当我向我的数据库添加新配方时我可以自动递增一个值。现在我正在使用 async.series 到 运行 种子文件中的不同任务。在我包含的内容中,您可以看到我在哪里设置 recipe_id 等于此方法 return value getNextSequence(counters, "recipeid")

getNextSequence 使用 Counter 模型来查询 (findOneAndUpdate) 数据库。我相信 findOneAndUpdate 的回调永远不会被调用,因为 async.series 的回调首先被调用。这是一个有趣的问题,因为我需要确保 getNextSequence 在继续之前已成功 returned。不确定解决此问题的最佳方法。

//seed.js //不完整

        var getNextSequence = require('./utils/getNextSequence').getNextSequence;

        recipes = new mongo.Collection(db, "recipes");
        counters = new mongo.Collection(db, "counters");

        async.series([
            function(callback){
                //initiate counter
                counters.insert(
                {
                  _id: "recipeid",
                    seq: 0
                },function(err, rec){
                        callback(err, rec);
                })

            },
            function(callback){
                //add test recipes

                recipes.insert([{
                    recipe_id: getNextSequence(counters, "recipeid"),
                    title:'title 1',
                    body:'body 1',
                    author: [seedUsers[1]._id],
                    categories: [ seedCategories[0]._id, seedCategories[1]._id ],
                    create_at: new Date()
                },{
                    recipe_id: getNextSequence(counters, "recipeid"),
                    title:'title 2',
                    body:'body 2',
                    author: [seedUsers[1]._id],
                    categories: [ seedCategories[1]._id ],
                    create_at: new Date()
                }], function(err, rec){
                    callback(err, rec);
                })
            }
        ],
        // optional callback
        function(err, results){
          //console.log('\n', results);
          db.close();
        });

//getNextSequence.js

var Counter = require('../counter').Counter;

exports.getNextSequence = function(counters, name) {

Counter.findOne({ '_id': 'recipeid' }, function (err, counter) {
  //if (err) return handleError(err);
  //never called
  console.log('---counter seq=', counter.seq);
})

Counter.findOneAndUpdate({ _id: name }, { $inc: { seq: 1 } }, { new: true }, function(err, counter){
 //never called
    console.log('counter.seq', counter.seq);
    return counter.seq;
  }
)

}

我不确定你使用的是哪个异步库,我们假设它是这个 https://github.com/caolan/async

您可能需要先 运行 getNextSequence,然后再插入收据。稍微更改 getNextSequence,以便 async 知道 findOneAndUpdate 过程何时完成。我也改为使用waterfall,所以一个任务的结果传递给下一个

var Counter = require('../counter').Counter;

exports.getNextSequence = function (counters, name, callback) {

  Counter.findOne({'_id': 'recipeid'}, function (err, counter) {
    //if (err) return handleError(err);
    //never called
    console.log('---counter seq=', counter.seq);
  })

  Counter.findOneAndUpdate({_id: name}, {$inc: {seq: 1}}, {new: true}, function (err, counter) {
      //never called
      console.log('counter.seq', counter.seq);
      callback(null, counter.seq);
    }
  )
}

播种

var getNextSequence = require('./utils/getNextSequence').getNextSequence;

recipes = new mongo.Collection(db, "recipes");
counters = new mongo.Collection(db, "counters");

async.waterfall([
    function (callback) {
      //initiate counter
      counters.insert(
        {
          _id: "recipeid",
          seq: 0
        }, function (err, rec) {
          callback(err, rec);
        })

    },
    function (callback) {
      getNextSequence(counters, "recipeid", callback);
    },
    function (seq, callback) {
      //add test recipes
      recipes.insert({
        recipe_id: seq,
        title: 'title 1',
        body: 'body 1',
        author: [seedUsers[1]._id],
        categories: [seedCategories[0]._id, seedCategories[1]._id],
        create_at: new Date()
      }, function (err, rec) {
        callback(err, rec);
      })
    },
    function (callback) {
      getNextSequence(counters, "recipeid", callback);
    },
    function (seq, callback) {
      //add test recipes
      recipes.insert({
        recipe_id: seq,
        title: 'title 2',
        body: 'body 2',
        author: [seedUsers[1]._id],
        categories: [seedCategories[1]._id],
        create_at: new Date()
      }, function (err, rec) {
        callback(err, rec);
      })
    }
  ],
  // optional callback
  function (err, results) {
    //console.log('\n', results);
    db.close();
  });