How to Run Async Functions in Parallel in JavaScript
To run async functions in parallel in JavaScript, use
Promise.all with an array of async function calls. This runs all functions at the same time and waits for all to finish, returning their results together.Syntax
Use Promise.all with an array of promises (async function calls). It returns a single promise that resolves when all promises resolve.
Promise.all([promise1, promise2, ...]): Runs all promises in parallel.- Returns an array of results in the same order as the input promises.
- If any promise rejects,
Promise.allrejects immediately.
javascript
Promise.all([asyncFunction1(), asyncFunction2(), asyncFunction3()]) .then(results => { // results is an array of resolved values }) .catch(error => { // handle error if any promise rejects });
Example
This example shows three async functions running in parallel using Promise.all. The total time is about the longest single async task, not the sum.
javascript
function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function task1() { await wait(1000); return 'Result 1'; } async function task2() { await wait(2000); return 'Result 2'; } async function task3() { await wait(1500); return 'Result 3'; } async function runParallel() { const results = await Promise.all([task1(), task2(), task3()]); console.log(results); } runParallel();
Output
["Result 1", "Result 2", "Result 3"]
Common Pitfalls
Common mistakes when running async functions in parallel include:
- Using
awaitinside a loop which runs tasks sequentially instead of parallel. - Not handling errors properly, causing unhandled promise rejections.
- Assuming order of completion matches order of calls (use
Promise.allto keep order).
javascript
async function wrong() { const results = []; for (const task of [task1, task2, task3]) { // This waits for each task to finish before starting the next results.push(await task()); } console.log(results); } async function right() { // Runs all tasks at the same time const results = await Promise.all([task1(), task2(), task3()]); console.log(results); }
Quick Reference
Tips for running async functions in parallel:
- Use
Promise.allto run multiple async calls simultaneously. - Handle errors with
try/catchor.catch()onPromise.all. - Use
Promise.allSettledif you want to wait for all promises regardless of errors. - Do not use
awaitinside loops if you want parallel execution.
Key Takeaways
Use Promise.all with an array of async calls to run them in parallel.
Promise.all returns results in the order of the input promises.
Avoid awaiting async calls inside loops to prevent sequential execution.
Handle errors properly to avoid unhandled promise rejections.
Use Promise.allSettled if you want to wait for all promises even if some fail.