dmx dmx - 13 days ago 8
Javascript Question

Javascript - How to handle promises correctly with loops?

I am using

promises
to handle list of task:

This is a sample of code:

var array = ["aaa", "bbbb", "cccc", "dddd", "eeee"];
var result = [];
var p = Promise.resolve({
then: function(onFulfill, onReject) {
array.forEach(function(x){
// http request with x and make sure this request ends before a new one if fired
// put http resolte in array : result.push(httpRespose);
});
//when done, onFulfill(result)
}
});
p.then(
function(v) {
console.log(v); // "fulfilled!"
}, function(e) {
console.log(e); // not called
});


I want to be able to make and http request using every element from array, then put result in an other array and when done return that new array. I also want to know if it is possible to make sure that http results are added in the same order (it is not very important).

Can someone please help ?

Answer

Promise.all is used to wait for a number of promises to fulfill.

Each time you create a promise, push it into an array and then use

Promise.all(myPromiseArray).then(allDoneHandler)

Here's an example:

var items = [ 500, 1000, 1500 ];
var results = [];
items.forEach((item) => {
  let promise = new Promise((resolve) => {
    setTimeout(() => {
        console.log(item);
        resolve(item);
    }, item);
  });
  results.push(promise);
});
Promise.all(results).then(() => {
    console.log('done!');
});