How to Use Promise.all with Async/Await in JavaScript
Use
Promise.all with async/await by passing an array of promises to Promise.all and awaiting its result. This runs all promises in parallel and waits until all are resolved or any rejects.Syntax
The basic syntax uses Promise.all with an array of promises inside an async function. You await the Promise.all call to get all results once all promises finish.
async function: Declares an asynchronous function.Promise.all([promises]): Takes an array of promises and returns a new promise that resolves when all input promises resolve.await: Pauses execution until thePromise.allpromise resolves.- Returns an array of results in the same order as the input promises.
javascript
async function runAll() { const results = await Promise.all([ promise1(), promise2(), promise3() ]); return results; }
Example
This example shows three asynchronous tasks simulated with setTimeout. Using Promise.all with async/await, all tasks run in parallel and the results are logged together after all finish.
javascript
function delay(ms, value) { return new Promise(resolve => setTimeout(() => resolve(value), ms)); } async function fetchAll() { const results = await Promise.all([ delay(1000, 'First'), delay(500, 'Second'), delay(1500, 'Third') ]); console.log(results); } fetchAll();
Output
["First", "Second", "Third"]
Common Pitfalls
Common mistakes include:
- Not using
awaitwithPromise.all, which returns a promise instead of resolved values. - Passing non-promise values or forgetting to wrap async calls in promises.
- Using
awaitinside a loop instead ofPromise.all, causing sequential instead of parallel execution. - Not handling rejections properly; if any promise rejects,
Promise.allrejects immediately.
javascript
async function wrongUsage() { // Sequential execution (slow) const results = []; for (const fn of [delay1, delay2, delay3]) { results.push(await fn()); // waits one by one } return results; } async function correctUsage() { // Parallel execution (fast) const results = await Promise.all([delay1(), delay2(), delay3()]); return results; }
Quick Reference
Tips for using Promise.all with async/await:
- Use
Promise.allto run promises in parallel and wait for all. - Always
awaitthePromise.allcall to get resolved results. - Handle errors with
try/catchbecausePromise.allrejects if any promise rejects. - Input promises can be any async operations like fetch calls or timers.
Key Takeaways
Use
await Promise.all([...]) to run multiple promises in parallel and wait for all to finish.Always handle errors with
try/catch because Promise.all rejects if any promise fails.Avoid awaiting promises inside loops to prevent sequential execution; use
Promise.all instead.The results array from
Promise.all matches the order of the input promises.Pass only promises or async functions to
Promise.all for correct parallel behavior.