简体   繁体   English

承诺链内循环

[英]Promise chain inside for loop

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

cleanupInstance is a promise chain as well. cleanupInstance也是一个承诺链。 However currently my for loop goes to the next iteration before the entire promise chain is completed. 但是,目前我的for循环在整个promise链完成之前进入下一次迭代。 Is there a way to promisify the loop as well? 有没有办法宣传循环? I am using Bluebird library (nodejs) for promises. 我正在使用Bluebird库(nodejs)进行承诺。

You could use .each : 你可以使用.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');
});

Why don't you use Promise.each or Promise.all ? 你为什么不使用Promise.eachPromise.all It would be more understandable and flexible. 这将更容易理解和灵活。

Please check the examples below. 请查看以下示例。

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

Or you may have loop in loop. 或者你可能有循环循环。 So just an example if you have array of arrays. 所以只是一个例子,如果你有数组数组。

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

Please explain what the code will be when there are multiple promise chains inside the all loop. 请解释当all循环中有多个promise链时代码是什么。
For instance: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM