When should I use Promise.all instead of awaiting one at a time?
Written by Jatin Thacker, Automation Architect · Updated
Promise.all when several pieces of async work do not depend on each other, so they can run at the same time and you wait once for all of them. Keep awaiting one at a time when each step needs the previous one to finish, which is true of most actions on a single page.This answer is one piece of Chapter 6: Async and Await.
- Error Handling & Debugging
- Callbacks & Promises
- Async/Await Mastery
- Practice and interview questions: Asynchronous JavaScript & Modern ES6+
Awaiting one at a time is correct but slow when the work is independent. Each await waits for one result before the next one even starts.
The example fakes three API calls that take 300 ms each. Awaited one by one, they take about 900 ms. Passed to Promise.all, all three start together, and the whole thing takes about 300 ms. The results come back as an array in the order you passed them in, not the order they finished.
That suits test setup: creating three orders through an API, or reading three files of test data. It does not suit clicks and fills on one page. Those are a sequence, where the second action depends on the first, and running them together only makes the test unpredictable.
Promise.all also fails fast. If any one Promise rejects, the whole call rejects with that first error, as the last part of the example shows with ORD-9999 not found. When you need every result, including the failures, use Promise.allSettled() instead.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fetchOrder = (id) => wait(300, `${id} loaded`);
const rounded = (start) => Math.round((Date.now() - start) / 100) * 100;
let start = Date.now();
const a = await fetchOrder('ORD-4100');
const b = await fetchOrder('ORD-4101');
const c = await fetchOrder('ORD-4102');
console.log('one at a time:', [a, b, c], `~${rounded(start)}ms`);
start = Date.now();
const all = await Promise.all(['ORD-4100', 'ORD-4101', 'ORD-4102'].map(fetchOrder));
console.log('Promise.all: ', all, `~${rounded(start)}ms`);
try {
await Promise.all([fetchOrder('ORD-4100'), Promise.reject(new Error('ORD-9999 not found'))]);
} catch (err) {
console.log('rejected:', err.message);
}one at a time: [ 'ORD-4100 loaded', 'ORD-4101 loaded', 'ORD-4102 loaded' ] ~900ms Promise.all: [ 'ORD-4100 loaded', 'ORD-4101 loaded', 'ORD-4102 loaded' ] ~300ms rejected: ORD-9999 not found
Promise.all with three API requests and the second one rejects. What happens?Practised in the full course: the drill forEach does not wait.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free