Promise.all vs await Promise.all example wrong

Viewed 335

I'm trying to see myself the different between Promise.all and await Promise.all. I have learnt that the first one ends earlier if one of the promises fail but in the same case with await we have to wait to the completion of all promises.

In my example, in both cases, they finish at the same time. What I'm doing wrong?

/**
 * Create a promise
 * @param ok true -> resolve, false -> reject
 */
function create_promise(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => ok ? resolve() : reject(), 2e3)
  })
}

// Finish as soon as I get a reject
Promise.all([create_promise(true), create_promise(false), create_promise(true)])
  .catch(() => console.log('rejected'))

// Finish after waiting all
const my_async_function = async () => 
  await Promise.all([create_promise(true), create_promise(false), create_promise(true)])

my_async_function().catch(() => console.log('rejected'))

1 Answers

await Promise.all will ensure that all the promises will be resolved before executing the line after the await.

/**
 * Create a promise
 * @param ok true -> resolve, false -> reject
 */
function create_promise(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => ok ? resolve() : reject(), 2e3)
  })
}

console.log("async/await version...")
const my_async_function = async () => {
  console.log("before await promise.all");
  const res = await Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after await  promise.all"); // This line will be executed only after all promises are successfully resolved
  return res;
  }
my_async_function().catch(() => console.log('rejected'))

console.log("without async/await version...")
const my_SYNC_function = () => {
  console.log("before promise.all");
  const res = Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after promise.all"); // This line will always be immediately executed after the Promise.all line, and not waiting for the promise completion  at all.
  return res; // So this line returns the return value of Promise.all, which will be an unresolved promise because the 2 seconds have not been elapsed yet.
  }
  
my_SYNC_function().catch(() => console.log('rejected'))

This has nothing to do with a Promise itself being somehow "executed faster".

However, the function that calls Promise.all without await returns earlier, it just returns some Promise that has not been resolved yet.

Related