循环内的承诺链

时间:2015-08-18 14:55:51

标签: javascript node.js promise bluebird

for (var i in listofInstances) {
        cleanupInstance(listofInstances[ i ])
        .then(function () {
            console.log("Done" + listofInstances[ i ])
        });
}

cleanupInstance也是一个承诺链。但是,目前我的for循环在整个promise链完成之前进入下一次迭代。有没有办法宣传循环?我正在使用Bluebird库(nodejs)进行承诺。

3 个答案:

答案 0 :(得分:8)

您可以使用.each

var Promise = require('bluebird');
...
Promise.each(listofInstances, function(instance) {
  return cleanupInstance(instance).then(function() {
    console.log('Done', instance);
  });
}).then(function() {
  console.log('Done with all instances');
});

答案 1 :(得分:2)

为什么不使用Promise.eachPromise.all?这将更容易理解和灵活。

请查看以下示例。

var Promise = require('bluebird');
var someArray = ['foo', 'bar', 'baz', 'qux'];

Promise.all(someArray.map(function(singleArrayElement){
  //do something and return
  return doSomethingWithElement(singleArrayElement);
})).then(function(results){
  //do something with results
});

Promise.each(someArray, function(singleArrayElement){
  //do something and return
  return doSomethingWithElement(singleArrayElement);
}).then(function(results){
  //do something with results
});

或者你可能有循环循环。所以只是一个例子,如果你有阵列数组。

var Promise = require('bluebird');
var arrayOfArrays = [['foo', 'bar', 'baz', 'qux'],['foo', 'bar', 'baz', 'qux']];

function firstLoopPromise(singleArray){
  return Promise.all(singleArray.map(function(signleArrayElement){
    //do something and return
    return doSomethingWithElement(signleArrayElement);
  }));
}


Promise.all(arrayOfArrays.map(function(singleArray){
  //do something and return
  return firstLoopPromise(singleArray);
})).then(function(results){
  //do something with results
});

答案 2 :(得分:0)

请解释当all循环中有多个promise链时代码是什么 例如:

Promise.all(someArray.map(function(singleArrayElement){
    //do something and return
    return doSomethingWithElement(singleArrayElement)
    .then(function(result){
    return doSomethingWithElement(result)
})
.then(function(result){
    return doSomethingWithElement(result)
})
})).then(function(results){
    //do something with results
});