javascriptnode.jsasync-awaitpromise

calling each element inside Promise.all with await


const results = await Promise.all([
  await asyncTask1(), await asyncTask2(), await asyncTask3()
]); 

Will the code snippet above produce a bug, or will it defeat the purpose of Promise.all as each element will be blocking the next while producing the expected correct result?


Solution

  • The operation of the code is sound but obscure:

    const results = await Promise.all([
      await asyncTask1(), await asyncTask2(), await asyncTask3()
    ]);
    

    waits for the fulfilled value of the three task results to be obtained before passing them to Promise.all to put then in an array for you, in the microtask queue, so you can await the resultant array (Promise.all returns a promise that fulfills with the results or throws if any are rejected).

    const results = [ await asyncTask1(), await asyncTask2(), await asyncTask3()];
    

    achieves the same result while maintaining the blocking of tasks until the previous one fulfills, but with less cycles through the Promise Job queue.

    If you don't want the tasks to block each other, leave out awaiting their results before calling Promise.all :

    const results = await Promise.all([
      asyncTask1(), asyncTask2(), asyncTask3()
    ]);