JavaScript

Run independent asynchronous tasks with Promise.all

Use Promise.all to await independent tasks together and receive results in input order. It rejects when an input promise rejects, even if other tasks are still running.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const delay = (value, ms) => new Promise(resolve => setTimeout(() => resolve(value), ms));
const results = await Promise.all([delay("first", 20), delay("second", 1)]);
console.log(JSON.stringify(results));

How it works

Calling delay starts both timers before the combined await. The second task finishes first, but the result array follows the order of the promises supplied to Promise.all. This is useful for independent work that does not need serial execution.

Limits and mistakes

Rejection does not automatically cancel the other tasks. Launching thousands of network requests at once can overload a service even though Promise.all itself is simple. Use a concurrency limit when the number of jobs is large.

Check the result

Expect ["first","second"]. Replace one input with a rejected promise inside try/catch and confirm your error handling. Do not infer completion order from result order.

Sources

Reference documentation for the behavior used in this guide: