0

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!

5
  • 2
    Can you provide a concrete example? I don't understand what you're trying to do. Commented Oct 2, 2017 at 20:46
  • Perhaps using generators will help? This explains it quite well: davidwalsh.name/async-generators Commented Oct 2, 2017 at 20:47
  • Promise.all takes an array. It doesn't matter how many promises it contains, or how that number relates to your iteration counter. Do you know how to use it with non-nested loops? Commented Oct 2, 2017 at 20:48
  • @Thijs No. If at all, async/await syntax will, but that leads to sequential instead of concurrent execution. Commented Oct 2, 2017 at 20:48
  • @Bergi I'd also point out that the Promise it returns is related only to the Array as it was passed. In other words, you can't push to the array you gave Promise.all while it is waiting and expect it to wait on the additional, pushed Promise. I have seen some trip on this. Commented Oct 2, 2017 at 20:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.