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

时间:2015-01-09 23:32:02

标签: javascript node.js mongodb mongoose

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

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

// 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;
  }
)

}

1 个答案:

答案 0 :(得分:0)

我不确定您使用的是哪个异步库,让我们假设它是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();
  });