for (var i in listofInstances) {
cleanupInstance(listofInstances[ i ])
.then(function () {
console.log("Done" + listofInstances[ i ])
});
}
cleanupInstance
is a promise chain as well. However currently my for loop goes to the next iteration before the entire promise chain is completed. Is there a way to promisify the loop as well? I am using Bluebird library (nodejs) for promises.
To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop. In this guide, you learn how async/await works and how it solves the problem of using promises in for loops.
Introduction to the JavaScript promise chainingThe callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).
The then method returns a Promise which allows for method chaining. If the function passed as handler to then returns a Promise , an equivalent Promise will be exposed to the subsequent then in the method chain. The below snippet simulates asynchronous code with the setTimeout function. Promise.
You could use .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
? 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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With