dmx dmx - 1 year ago 120
Javascript Question

Javascript - How to handle promises correctly with loops?

I am using

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) {
// 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)
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 Source

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


Here's an example:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download