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

3 Answers 3

8

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');
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

Please explain what the code will be when there are multiple promise chains inside the all loop.
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
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.