在Promise中嵌套Promise

Nested Promise in Promise each

本文关键字:Promise 嵌套      更新时间:2023-09-26

有人能解释一下为什么这不能像我预期的那样工作吗?

我试图只返回在Promise.ech().then()中使用的已创建或更新项的id。这是必要的,因为create返回一个对象并更新一个对象数组。

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

结果是整个创建的对象,而不仅仅是id。我想返回一个只包含更新后的id的数组。显然嵌套承诺是不好的,但我不知道如何简化它。

不要使用.each使用.map将项目列表映射到项目列表:

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

如果你想一个接一个地查看它们并等待它们,你可以链接第二个.map。如果您想设置为按顺序执行(慢得多),.map还需要一个并发参数。

正如Esailija所说,在3.0中,each的行为会改变以返回结果,因此您的原始代码可能无效,但实际上在3.0中可以工作。