承诺链内循环

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

cleanupInstance也是一个承诺链。 然而,目前我的for循环在完成整个承诺链之前进入下一个迭代。 有没有办法让promisify这个循环呢? 我正在使用蓝鸟库(nodejs)承诺。

你可以使用.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'); }); 

你为什么不使用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 }); 

请解释在所有循环内有多个承诺链时代码将会是什么。
例如:

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