Kevin Heirich
Kevin Heirich

Reputation: 119

Mongoose async promise don't seem to work

I have a little trouble using the async' with mongoose. Basically my code is the following :

function() {
   SchemaOne.findById(fooIdOne).exec().then( x => {
      // Some first instructions
      myCollection.foreach( y => {
         SchemaTwo.findById(fooIdTwo).exec().then( z => {
            // Some second instructions
         });
      });
   }).then(() => {
      // Code to execute after
   });
}

Here I would like the "first instructions" and "second instructions" to be made BEFORE the "code to execute after", but the last "then" don't seem to wait for the second instructions to be made.

Could use a little help ! Many thanks ! Kev'.

Upvotes: 0

Views: 29

Answers (1)

trincot
trincot

Reputation: 350107

Your forEach call is executed synchronously and you don't return a promise in the then callback.

You should collect the promises that are created in the loop, and return a Promise.all of those.

function() {
   SchemaOne.findById(fooIdOne).exec().then( x => {
      // Some first instructions
      let promises = [];
      myCollection.foreach( y => {
         promises.push(SchemaTwo.findById(fooIdTwo).exec().then( z => {
            // Some second instructions
         }));
      });
      return Promise.all(promises);
   }).then(() => {
      // Code to execute after
   });
}

Upvotes: 2

Related Questions