exilonX exilonX - 5 months ago 47
Node.js Question

Chaining mongoose promises in a for loop

I have an api that creates a new document in mongodb using this function:

export function create(req, res) {
return Track.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}


This just adds a new document, I would like to extend this and after the document was added I would like to add some more documents into another collection with the information from the response, something like this:

export function create2(info) {
var trackId = info._id;
var users = info.users;

var basic = {
trackId : trackId
};

for (let user of users) {
basic.username = user.username;

Location.create(basic);
}
}


I would like to call the create2 function on a .then of the promise from the first create function something like this:

export function create(req, res) {
return Track.create(req.body)
.then(create2)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}


The problem is that create2 does not return a promise and I don't really know how to chain the promises returned by Location.create in create2?

Answer

The way to make create2 return a promise is with Promise.all(), which is fulfilled when the array of promises passed to it are all fulfilled. Something like this...

var _ = require('underscore');   // optional but useful for a better loop with '.map'

export function create2(info) {
  var trackId = info._id;
  var users = info.users;

  var basic = {
    trackId : trackId
  };

  var promises = _.map(users, function(user) {
    basic.username = user.username;
    return Location.create(basic);
  });
  return Promise.all(promises);
}
Comments