Trung Tran Trung Tran - 2 years ago 201
Javascript Question

Writing nested promise javascript es6

does anyone have any guides or tips on how to write a nested promises?

I am trying to turn the following nested

for loop
into a promise:

let arr = [1, 2, 3, 4, 5]


for (i = 0; i < arr.length ; i++) {

for (j = i + 1; j < arr.length ; j++) {

// call another asynchronous function

}

}


I thought about doing
Promise.all
, but the iterator in the inside
for
loop starts at
j = i + 1
so I wasn't sure how to handle this with
Promise.all
.

Thanks in advance!

Answer Source

Push them into an array

let arr = [1, 2, 3, 4, 5]
const promises = []
for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    promises.push(new Promise((resolve, reject) => {
      setTimeout(resolve, 100, [i,j]);
    }));
  }
}
Promise.all(promises).then(values => {
  console.log(values);
});

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