Sequential or parallel, and the forEach trap
for...of with await runs steps one by one, while Promise.all over map starts them together. The choice depends on whether the steps depend on each other: dependent steps and rate limits call for sequence, independent data for parallelism with limited concurrency, for example p-limit. forEach with an async callback does not wait for promises: the loop ends at once and errors become unhandled, and the same goes for filter and some.
TypeScript · Async
Ten deletions of 200 ms take two seconds. Can it be faster and why will forEach not help here?
Cleanup after a test deletes ten accounts and each deletion takes 200 ms. A loop with await spends two seconds and over hundreds of tests that is minutes. Someone suggests a «simplification»: replace the loop with ids.forEach(async id => await api.delete(id)). The run suddenly gets fast, but sometimes the next test sees someone else's data and errors from another test show up in the logs. This lesson is about choosing between sequential and parallel execution and why forEach with an async callback breaks both.
How it works and why. await inside a for...of loop suspends the function itself, so the next iteration starts only after the previous one finishes: this is sequential execution, times add up. map with Promise.all first creates all promises (all requests start almost at once) and then waits for them together: the time equals the longest operation, not the sum.
Time: a loop with await versus Promise.all
// sequential: 10 requests of 200 ms = ~2 s
for (const id of ids) {
await api.deleteAccount(id);
}
// parallel: ~200 ms
await Promise.all(ids.map((id) => api.deleteAccount(id)));
When sequential. The steps depend on each other or the order matters: deposit, then transfer, then a balance check. Also when the API has a rate limit or handles one account unreliably under parallel requests.
// the steps depend on each other: sequential only
await api.deposit(account.id, 500);
await api.transfer(account.id, other.id, 200);
const balance = await api.getBalance(account.id);
expect(balance).toBe(300);
When parallel. Independent operations: creating several accounts, cleanup, calls to different services. For big arrays a concurrency limit is needed, otherwise a couple of hundred simultaneous requests will knock over the test environment or hit limits:
async function mapLimit<T, R>(
items: readonly T[],
limit: number,
fn: (item: T) => Promise<R>,
): Promise<R[]> {
const results: R[] = new Array(items.length);
let next = 0;
async function worker(): Promise<void> {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i] as T);
}
}
const count = Math.min(limit, items.length);
await Promise.all(Array.from({ length: count }, worker));
return results;
}
await mapLimit(ids, 5, (id) => api.deleteAccount(id));
This is a minimal «pool»: five workers take the next item in turn and the results sit at the same indexes as the input. A project usually takes a ready library such as p-limit.
The forEach trap. forEach calls the callback for every element and ignores what it returns. An async callback returns a promise nobody awaits, so the loop ends right after starting all the callbacks:
ids.forEach(async (id) => {
await api.deleteAccount(id);
});
console.log('done');
// "done" is printed BEFORE the deletions and errors become unhandled rejections
The test goes on, checks run on dirty data, and the deletion error becomes an unhandled rejection that may appear in the next test. The same goes for filter, some, find and every: they expect a synchronous result and a promise is always truthy. TypeScript does not help here: the callback may return anything, so this compiles without errors.
// wrong: a promise is always truthy, so everything passes
const active = accounts.filter(
async (a) => (await api.getStatus(a.id)) === 'ACTIVE',
);
// right: statuses first, then a synchronous filter
const statuses = await Promise.all(accounts.map((a) => api.getStatus(a.id)));
const activeOk = accounts.filter((_, i) => statuses[i] === 'ACTIVE');
reduce is similar: an async reducer works sequentially only if the accumulator is awaited explicitly, and the code becomes hard to read. A simpler choice: for...of when the order matters and Promise.all(items.map(...)) when it does not.
Limits and alternatives. Parallel requests do not guarantee completion order, so any code that depends on it will break. Shared state (a counter, an array everyone appends to) in parallel callbacks is best avoided. Separately: parallelism between Playwright tests is provided by the runner through workers, so extra parallelism inside one test is needed for data preparation, not for the scenario steps. For building big data sets a single bulk API request is often better than hundreds of small ones.
Common mistakes.
forEach(async ...)for requests: the loop does not wait and errors become unhandled.filter(async ...): the filter does not filter because a promise is always truthy.Promise.allover a thousand requests without a limit: an overloaded environment or 429.- A sequential loop for independent cleanup: the test is slow for no reason.
- Running dependent steps in parallel (deposit and transfer): the result depends on a random order.
Check yourself
In accounts.filter(async a => (await api.getStatus(a.id)) === 'ACTIVE') every account lands in the result. Why and how to fix it?
Answer
The async callback returns a Promise and filter checks it for truthiness: a promise is always truthy no matter how it ends. The fix: get the statuses through Promise.all and filter synchronously by index.
A cleanup of 500 accounts was done with Promise.all(ids.map(...)) and the server started answering 429. What to change without returning to a fully sequential loop?
Answer
Limit concurrency: process in chunks or with a pool of a few workers (p-limit or your own mapLimit), for example 5-10 at a time. The time stays much lower than sequential and the load on the API is under control.
for...of with await runs requests one by one, Promise.all with map in parallel. The choice depends on whether the steps depend on each other. forEach with an async callback must not be used: it does not wait. Middle/Senior: Dependent steps and rate limits mean sequential, independent data means parallel with a limit (p-limit or a pool). forEach, filter, some ignore promises, so in async code I replace them with for...of or Promise.all, and this is visible only to the linter (no-misused-promises) because the compiler gives no error.