ArKi
ArKi

Reputation: 701

How do I make sure a looping save to the database executes before done() in Mocha?

I am running the following code as a parameter to before() to create test entries in my MongoDB database (using Mongoose). However, this results in an error because done() is called multiple times. However, if I don't use done(), then the testPhoto won't save to the database because it is handed off to a background thread.

var createFeed = function(done) {
  for (var i = 1; i <= 10; i++) {
    var testPhoto = new Photo({ owner   : 'test' + (i % 2),
                            caption : 'test caption',
                            ratings : [{ _id   : 'test' + (i % 3),
                                        rating : 5 }] });
    testPhoto.save(done);
  }
}

Is there any way to guarantee that the done() function executes only once, after all the testPhoto's have been saved to the database?

Upvotes: 0

Views: 128

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311955

You can do something more formal with async, or you can take a simpler approach where you just keep track of the number of save operations outstanding and call done when they've all completed:

var createFeed = function(done) {
  var saves = 10;
  for (var i = 1; i <= 10; i++) {
    var testPhoto = new Photo({ owner : 'test' + (i % 2),
                            caption : 'test caption',
                            ratings : [{ _id   : 'test' + (i % 3),
                                        rating : 5 }] });
    testPhoto.save(function(err){
      if (--saves === 0) {
        done();
      }
    });
  }
}

Upvotes: 4

Related Questions