glasspill
glasspill

Reputation: 1300

Nested Promise in Promise each

Can someone explain why this doesn't work as I expect it?

I am trying to return only the id of the created or updated items to use in the Promise.each().then(). This is necessary because create returns an object and update an array of objects.

Promise.each(items, function(item){
  if(...item doesn\'t exist...)
    return Item.create(item)
     .then(function (created) {
        return created.id;
        ///HOW DO I GET THIS ID ONLY?
      });
  else {
   return Item.update(item)
     .then(function (updated) {
        return updated[0].id;
        ///AND THIS ID?
      });
   }

}).then(function(result) {
  sails.log("THIS SHOULD BE AN ID" + JSON.stringify(result));
});

result is the whole created object, instead of just the id. I want to return an array of just the updated ids. Apparently nesting promises is bad, but I don't know how i could simplify this.

Upvotes: 1

Views: 1334

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

Don't use .each use .map to map a list of items to a list of items:

Promise.map(items, function(item){
  if(...item doesn\'t exist...)
    return Item.create(item).get("id"); // get is a shortcut to .then(fn(x){ r x.id; })
  else {
   return Item.update(item).get(0).get(id);
}).then(function(result) {
  sails.log("Here is the array of all IDs + JSON.stringify(result));
});

If you want to go over them one by one and wait for them, you can chain a second .map. If you want to set to do them sequentially (much slowe) - .map also takes a concurrency parameter.

As Esailija said - in 3.0 the behavior of each changes to return the results so your original code would have been ineffective but would have actually worked in 3.0 .

Upvotes: 3

Related Questions