Promise.all, allSettled, race, any
Promise.all rejects on the first error, allSettled reports every outcome, race takes the first to settle and any the first to succeed. A promise starts when it is created and a combinator only observes it, so nothing is cancelled. Cleanup uses allSettled and reads the results, and a race timeout is not a cancellation: that needs an AbortSignal or the request's timeout option.
TypeScript · Async
One of ten cleanup requests failed and the other nine were not deleted. Which method to wait with?
Cleanup after a test deletes ten created accounts with Promise.all. One request returns an error and the whole await rejects at once. The question arises: were the other nine deleted or left as garbage in the environment, and why does a test that supposedly cleans up leave data behind. Every «wait for several promises» task has its own combinator, and the choice depends on what should happen with an error and whether the result of each is needed.
How it works and why. A promise starts working when it is created, not when it is awaited: api.deleteAccount(id) has already sent its request. Combinators only observe promises that are already running and sum them up by their own rule. Two consequences follow. First: no combinator cancels anything when another promise «wins» or an error happens, the rest keep running in the background. Second: the start order is decided by where you created the promise, not where you wrote await.
| Method | Settles | Result |
|---|---|---|
Promise.all | all fulfilled or the first rejection | array of values or the first error |
Promise.allSettled | when all have settled | array of { status, value | reason } |
Promise.race | the first one settled either way | its value or error |
Promise.any | the first fulfilled | a value or AggregateError if all failed |
Promise.all is for independent setup steps that must all pass. Tuple types are preserved:
const [sender, receiver] = await Promise.all([
api.createAccount({ currency: 'UAH', balance: 100_000 }),
api.createAccount({ currency: 'UAH', balance: 0 }),
]);
// sender and receiver keep their own types, not a union
If one promise rejects, all rejects at once but the other requests are not cancelled. If they created data, «garbage» stays in the environment and you will no longer learn about their errors. Those errors do not become unhandled: all subscribes to every promise.
Example: cleanup that does not stop at the first error. Cleanup needs «try everyone and learn who failed»:
const results = await Promise.allSettled(
createdIds.map((id) => api.deleteAccount(id)),
);
const failed = results.filter(
(r): r is PromiseRejectedResult => r.status === 'rejected',
);
if (failed.length > 0) {
console.warn('Cleanup failed for ' + failed.length + ' items');
}
allSettled never rejects, and the narrowing predicate r is PromiseRejectedResult gives TS access to reason. In the failure report show the id and the reason, not just the count.
Example: an action and the response it triggers. A classic Playwright mistake is starting the wait after the action:
await page.getByRole('button', { name: 'Send' }).click();
const response = await page.waitForResponse('**/api/transfers');
// the response may have come during click: waitForResponse waits forever
When to start waiting for the response
Action first, wait second
A fast response arrives during click. The subscription starts later, the event is missed, the test waits until the timeout.
The wait is created before the action
The wait promise is already listening when the click happens. Promise.all just collects both results.
Promise.all is present.const [response] = await Promise.all([
page.waitForResponse(
(r) => r.url().includes('/api/transfers') && r.request().method() === 'POST',
),
page.getByRole('button', { name: 'Send' }).click(),
]);
expect(response.status()).toBe(201);
The same without Promise.all: keep the wait promise in a variable before the click and await it afterwards:
const responsePromise = page.waitForResponse('**/api/transfers');
await page.getByRole('button', { name: 'Send' }).click();
const response = await responsePromise;
The second form reads better when there are other steps between the action and the response. Both are fine, and the assertion on response goes after them.
Limits and alternatives. Promise.race does not stop the losers. A typical use, a timeout:
const result = await Promise.race([
api.getReport(id),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('report timeout')), 5_000),
),
]);
// getReport is not cancelled after the timeout: it keeps running in the background
This only abandons the wait while the request continues and may change data later. Also the timer is never cleared: after a fast response it keeps the process alive for 5 more seconds, so keep its id and call clearTimeout in finally. Real cancellation needs support in the API itself: AbortSignal.timeout(ms) for fetch or the timeout option of Playwright requests. Promise.any fits «take the first working one» (several environment mirrors). If all fail you get an AggregateError with the errors array:
try {
const first = await Promise.any([api.get('/a'), api.get('/b')]);
} catch (e) {
if (e instanceof AggregateError) console.log(e.errors.length + ' failed');
}
For hundreds of items neither all nor allSettled without a concurrency limit is suitable: every request starts at once. That is the topic of the next lesson.
Common mistakes.
Promise.allin cleanup: the first error hides the results of the rest and part of the data stays.- The response wait is created after the click: the event is missed and the test waits until the timeout.
racewith a timer as «cancellation»: the losing operation keeps running.- Awaiting
allSettledand ignoring the results array: errors disappear without a trace. - Passing promises that depend on each other to
all: the result depends on a random order.
Check yourself
Cleanup calls await Promise.allSettled(ids.map(deleteAccount)) and nothing else. One DELETE returned 500. What will the test see?
Answer
Nothing: allSettled does not reject and nobody reads the statuses array. The test goes green and the account stays in the environment. You must filter status === 'rejected' and at least log it, and for critical cleanup throw an error.
Why does await click() before waitForResponse(...) sometimes wait until the timeout while Promise.all([waitForResponse(...), click()]) does not?
Answer
After await click() the wait is created only once the click has finished, and a fast response may already have arrived. In Promise.all both promises are created synchronously in one expression, before Node processes any network event, so the subscription already exists. What matters is whether the wait is created before the first await, not the order of the array items: waitForResponse goes first only for readability.
Promise.all waits for all and fails on the first error, allSettled waits for all and gives the status of each, race takes the first settled, any the first fulfilled. Middle/Senior: A promise starts at creation and a combinator only observes, so nothing is cancelled. For cleanup I take allSettled and read the results, for a response wait I create the promise before the action, and I do not treat a timeout through race as cancellation: I use AbortSignal or the timeout option of the request itself.