简体   繁体   中英

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

I've got a seed file setup to populate my mongodb. I am setting up a counter so I can automatically increment a value when I add a new recipe to my db. Right now I'm using async.series to run the different tasks in the seed file. In what I've included you can see where I set recipe_id equal to this methods return value getNextSequence(counters, "recipeid")

getNextSequence uses the Counter model to query (findOneAndUpdate) the db. I believe the callback for findOneAndUpdate is never called though because the callback for async.series is invoked first. It's a funny problem though because I need to ensure that getNextSequence has returned successfully before moving on. Not sure the best way to go about this.

//seed.js //incomplete

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

}

I'm not sure which async library you're using, let's assume it is this https://github.com/caolan/async

You may want to run the getNextSequence first, before inserting the receipts. Changes the getNextSequence a little bit, so that the async know when the findOneAndUpdate process is done. I also changed to use waterfall , so the result from one task is passed to the next

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

seeding

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM