coolpasta
coolpasta

Reputation: 755

How can I make Promise.all wait for every promise?

I have the code:

const testPromise = (stepNumber) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('Done with step ' + stepNumber);
      resolve()
    }, 1000);
  });
}

const testPromiseAll = () => {
  return Promise.all([
    [1, 2, 3].map(number => {
      return testPromise(number);
    })
  ]);
}

testPromiseAll().then(() => {
  console.log('Done with all!');
});

And the message 'Done with all' should appear right after all the promises inside the .all are resolved...or so I thought. Reading the spec, as well as this article:

https://dev.to/dance2die/promise-race-vs-promise-any-and-promise-all-vs-promise-allsettled-26if

It seems that it should be the case, but it's not happening.

I would like the Promise.all to resolve if all promises inside are resolved and like-wise, if ANY of the promises inside are rejected, the whole chain should fail.

What can I do?

Upvotes: 1

Views: 47

Answers (1)

Alex R
Alex R

Reputation: 3311

You need to change:

const testPromiseAll = () => {
  return Promise.all([
    [1, 2, 3].map(number => {
      return testPromise(number);
    })
  ]);
}

to:

const testPromiseAll = () => {
    return Promise.all(
        [1, 2, 3].map(number => {
            return testPromise(number);
        })
    );
}

Your code passes a list of lists to the Promise.all function which resolves immediately.

Upvotes: 2

Related Questions