在循环中解决一个承诺

时间:2016-10-19 20:00:56

标签: javascript angularjs node.js promise

我遇到了如何解决并从链式承诺传回数据的问题。我正在使用节点js,请求承诺。这是我的代码

start(name)
   .then(firstFunction)
   .then(secondFuntion)
   .then(function(){
       // i want to return data from secondfunction  back  
   ))

问题在于secondFunction我有一个for循环,它对我从firstFunction获得的每个对象执行调用,firstFunction是一个对象数组。在每次迭代后或所有迭代后我都会解决这个问题。创建一个全局对象并将结果保存到该对象并返回该结果会更聪明吗?我的secondFunction代码看起来像这样

var secondFunction = function(data){
    var promise = new Promise(function(){
        for(var i= 0; i <data.length; i ++){
            options = { url: "", jason: true}
            rp.(options)
              .then(function(resp){
                // i do something with respose and need to save this 
               //should i resolve the promise here??
              })
              .catch(function(err){
              });
        }
    });
    return promise;
}

修改

我明白了!感谢所有的帮助,在我的第二个功能中,我做了这个

var task = function(item){
     // performed the task in here
}

var actions = data.map(task);
return Promise.all(actions);

1 个答案:

答案 0 :(得分:0)

对数组中的每个项执行异步操作的正常模式是将操作转换为返回Promise的函数,然后使用[].map()将值数组映射到数组中承诺。然后使用Promise.all(),它接受​​一个Promises数组,并在原始数组中的所有Promise被解析时返回一个使用值数组解析的Promise。它看起来像这样:

var secondFunction = function(data) {
  var promisesArray = data.map(rp);
  return Promise.all(promisesArray);
}

第三个.then()将根据rpdata中每个项目的data按照const secondFunction = data => Promise.all(data.map(rp)); 中出现的顺序解析后,已解决了一系列值。

带有一些ES6糖的较短版本是:

Promise.map()

如果您正在使用Bluebird,它是服务器端JS的事实上的promise库,您可以使用接受数组和映射函数的简写const secondFunction = data => Promise.map(data, rp); ,并执行相同的操作:

multiSelect
相关问题