【问题标题】:Promises in foreach [duplicate]foreach 中的承诺 [重复]
【发布时间】:2015-12-11 21:14:20
【问题描述】:

我有一些关于某些逻辑的代码。

我的以下代码块按预期工作,因此 willbeUpdated 变量无法以同步方式逐字更新。

var willbeUpdated = 1;
anArray.forEach(function(i){
   getPromisedData(i).then(function(d){
       willbeUpdated += d;
   });

});
if (wiillbeUpdated == something) {
  // some logic
}

所以问题是,我是否必须为该 foreach 逻辑再次创建另一个承诺的方法并将outside if logic 放在其 then 方法中,这将是最佳实践,还是在这种情况下任何其他更可取的想法?

编辑:我问这个问题是为了听听关于嵌套异步函数处理而不是确切的代码块的最佳或更好的方法,谢谢。

【问题讨论】:

    标签: javascript node.js foreach promise


    【解决方案1】:

    使用Promise.all()

    var willbeUpdated = 1,
        promises = [];
    anArray.forEach(function(i){
       promises.push(getPromisedData(i));
    });
    Promise.all(promises).then(function() {
      // some logic
    });
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是将 if 块 (willBeUpdated == something) 放入 getPromisedData 解析的函数中。

      所以:

      var willbeUpdated = 1;
      anArray.forEach(function(i){
         getPromisedData(i).then(function(d){
             willbeUpdated += d;
             if (wiillbeUpdated == something) {
               // some logic
             }
         });
      
      });
      

      会解决的。如果您可以让我更好地了解您正在尝试做什么,那么可能会有更好的解决方案。

      【讨论】:

      • 在简单递增的情况下,它可以工作,但不会等待所有任务结束,而是在完成任务之前做一些事情。
      • 这样,if逻辑将作为数组长度计数运行。
      【解决方案3】:

      q 和许多其他 Promise 库可以处理 Promise 数组,并等待它们的结果。

      var q = require('q');
      var willbeUpdated = 1;
      var todo = [];
      
      anArray.forEach(function(i){
        todo.push(getPromisedData(i).then(function(d) {
          return (willbeUpdated+= d);
        }));
      });
      
      q(todo).then(function() {
        if (wiillbeUpdated == something) {
          // some logic
        }      
      });
      

      【讨论】:

      • 您和@Gothdo 的答案似乎还可以,但问题不在于代码完全正确,例如,在嵌套循环中推动承诺返回值以获取其最新值将是丑陋的,这种解决方案是唯一的方法吗?
      猜你喜欢
      • 2019-05-03
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多