Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 659
user1692342 Avatar asked Aug 18 '15 14:08

user1692342


People also ask

How do you put a promise inside a for loop?

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.

Can promise be chained?

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 ).

What is then in promise?

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.


2 Answers

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');
});
like image 182
robertklep Avatar answered Oct 04 '22 08:10

robertklep


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
});
like image 24
Roman Sachenko Avatar answered Oct 04 '22 08:10

Roman Sachenko