QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript

Asynchrony: Promise, async/await, parallelism

Promise, async/await and a forgotten await

Without await a promise runs in the background and a test can pass without verifying anything. An async function always returns a Promise, and await is needed for everything that returns one, including locator actions and web-first assertions. The compiler catches only some cases, so the no-floating-promises and missing-playwright-await rules are enabled, and inside try you write return await.

TypeScript · Async

The test is green in 40 ms and nobody clicked the button. Where did the await go?

A test «transfer is created» passes in a few dozen milliseconds. The trace shows the click started but the test had already finished, and sometimes the run fails with «Target page, context or browser has been closed». The code looks fine and there are no type errors. The cause is two missing await words. This lesson explains what happens without them, where await is required and where it is not, and how to catch the mistake automatically.

How it works and why. An async function always returns a Promise: even with return 5 inside, from outside it is Promise<number>, and a throw becomes a rejected promise. Calling it runs the function synchronously up to the first await and immediately returns the promise. await does two things: it suspends this function until the promise settles and hands control back to the event loop, then either gives the value or throws the error. Without await nothing is suspended: the line runs, the promise goes to the background, the next line starts at once. The browser action is already sent, but the test neither waits for it nor sees its error.

A test without await ends before the action

testendclick()still running…
Figure 1. A test ends when its body ends, not when every started promise has settled.

Example: from a falsely green test to a real check. The starting code:

test('transfer is created', async ({ page }) => {
  page.getByRole('button', { name: 'Send' }).click();
  expect(page.getByText('Transfer sent')).toBeVisible();
});
// both calls return a Promise that nobody awaits

There are two problems. The click may not finish before the test ends, and expect(locator).toBeVisible() returns a promise: if nobody awaits it, the check guarantees nothing and the test may pass without it. The fix:

test('transfer is created', async ({ page }) => {
  await page.getByRole('button', { name: 'Send' }).click();
  await expect(page.getByText('Transfer sent')).toBeVisible();
});

The rule for where await is needed: everything that returns a Promise. In Playwright those are locator and page actions (click, fill, goto), reads from the browser (textContent, isVisible, count), web-first assertions (toBeVisible, toHaveText), expect.poll, expect(promise).resolves/rejects and any of your own async helpers. A plain expect(value).toBe(x) is synchronous: no await there.

What the compiler catches and what the linter catches. The compiler sees only part of the cases. A promise in an if condition it rejects:

// isVisible() returns Promise<boolean>
if (page.getByText('Cookies').isVisible()) {
  await page.getByRole('button', { name: 'OK' }).click();
}
// TS2801: This condition will always return true since this
// 'Promise<boolean>' is always defined.

A «floating» promise as a standalone expression the compiler lets through. For that there are type-aware ESLint rules (they need a type-aware config, for example parserOptions.projectService): @typescript-eslint/no-floating-promises finds promises nobody handled, @typescript-eslint/await-thenable finds await on a value that is not a promise, and the eslint-plugin-playwright plugin has missing-playwright-await for Playwright methods in particular. Also a Promise<void> return type on Page Object methods shows that a method is asynchronous.

Limits and traps. A forgotten await does not always give a green test. If the action fails and nobody awaits the promise, you get an unhandled rejection: in plain Node (since version 15) that ends the process with code 1, while a test runner decides itself which test to blame, so the failure can show up in another test. One more trap: return without await inside try. The function returns the promise and leaves the try before it settles, so the rejection does not reach the catch of the same function:

async function loadBalance(id: string): Promise<number> {
  try {
    return client.getBalance(id);       // no await
  } catch {
    return 0;                           // the error never gets here
  }
}
// inside try you need: return await client.getBalance(id);

The @typescript-eslint/return-await rule in in-try-catch mode requires exactly this. Outside try an extra return await gives nothing.

Common mistakes.

  • await on the action only and forgotten on expect(...).toBeVisible(): the check guarantees nothing.
  • if (locator.isVisible()) without await: the condition is always true (TS2801 only with strictNullChecks).
  • await where the value is synchronous: harmless but noise, and await-thenable flags it.
  • return promise inside try: the error bypasses catch and finally runs before the operation finishes.
  • A linter without a type-aware config: no-floating-promises does not work, and few people notice the config error.

Check yourself

A test has page.getByRole('button').click(); without await, and the next line is await expect(page).toHaveURL(/done/) with await. Is it safe?

Answer

No. The URL check will wait, but the click may happen after it starts or fail with an error nobody sees. The test depends on a random order of events and can be flaky. The action must be awaited just like the assertion.

Why does return client.get() inside try not reach the catch, while return await client.get() does?

Answer

Without await the function hands the promise out and leaves the try at once, and the rejection happens in the caller's code. With await the function waits inside try, so the rejection becomes an exception right there.

In an interview. Junior: An async function returns a promise and await waits for its result. A forgotten await in a test means the action or assertion is not waited for, so the test may pass without checking anything. Middle/Senior: Without await the promise goes to the background, the test ends with its body, and the rejection becomes an unhandled rejection in another test. So I enable no-floating-promises and missing-playwright-await with a type-aware config, and write return await inside try. The compiler catches only some cases, such as a promise in a condition, so it cannot be covered without a linter.

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.

MethodSettlesResult
Promise.allall fulfilled or the first rejectionarray of values or the first error
Promise.allSettledwhen all have settledarray of { status, value | reason }
Promise.racethe first one settled either wayits value or error
Promise.anythe first fulfilleda 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

Wrong

Action first, wait second

A fast response arrives during click. The subscription starts later, the event is missed, the test waits until the timeout.

Right

The wait is created before the action

The wait promise is already listening when the click happens. Promise.all just collects both results.

Figure 1. What matters is when the wait promise is created, not whether 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.all in 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.
  • race with a timer as «cancellation»: the losing operation keeps running.
  • Awaiting allSettled and 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.

In an interview. Junior: 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.

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

loop id 1DELETEloop id 2DELETEloop id 3DELETEall id 1DELETEall id 2DELETEall id 3DELETE
Figure 1. Parallelism saves time but the order goes away with it: the steps must be independent.
// 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:

How the worker pool works

async function mapLimit<T, R>(
  items: readonly T[],
  limit: number,
  fn: (item: T) => Promise<R>,
): Promise<R[]> {
  const results: R[] = new Array(items.length);
1  let next = 0;
  async function worker(): Promise<void> {
    while (next < items.length) {
2      const i = next++;
3      results[i] = await fn(items[i] as T);
    }
  }
  const count = Math.min(limit, items.length);
4  await Promise.all(Array.from({ length: count }, worker));
  return results;
}

await mapLimit(ids, 5, (id) => api.deleteAccount(id));
  1. Counter: the index of the next item, shared by all workers.
  2. Claim: next++ runs before the await, so two workers never take the same item.
  3. Result: is written at index i, so the result order matches the input order.
  4. Start: count workers start and Promise.all waits for all; at most limit requests run at once.
Figure 2. The numbers mark four key places in the code, not line numbers.

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.all over 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.

In an interview. Junior: 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.

Error handling in asynchronous code

In test code an error must reach the report with its true cause, so it is not swallowed but, when needed, rethrown with context and cause. An error in an async function becomes a rejected promise, and try/catch sees only the promises awaited inside it. The catch variable has type unknown and needs narrowing, and cleanup goes to a fixture, where the code after use() runs even after a failure.

TypeScript · Async

Creating the account «successfully» returned undefined. Where did the 500 error go?

The createAccount helper was wrapped in try/catch so it would «not fail over trifles». A week later tests fail in random places: «Cannot read properties of undefined (reading 'id')». The real cause, a 500 response from the API, was long ago swallowed in the helper. Error handling in test code has a different purpose than in a product: not to keep the system alive but to show the true cause of a failure as close as possible to where it happened.

How it works and why. An error in an async function becomes a rejected promise. await turns it back into an exception right at the place where it stands, so try/catch around await works as in synchronous code. But try/catch sees only the promises that are awaited inside it. A promise without await goes past:

async function run() {
  try {
    api.deleteAccount('acc-1');        // no await
  } catch {
    console.log('handled');            // never runs
  }
}

The rejection of such a promise becomes an unhandled rejection. An alternative to await with try/catch is .catch() on the promise itself: both ways are equivalent, but mixing them in one expression is not advisable.

Example: do not swallow, add context. The initial helper:

async function createAccount(): Promise<Account | undefined> {
  try {
    return await api.post('/accounts', { currency: 'UAH' });
  } catch {
    return undefined;   // a 500 and a timeout became "just no account"
  }
}

It turns a 500, a timeout and a network failure into the same undefined and the cause can no longer be recovered. Better to catch nothing, and if you do catch, rethrow with context. The cause option (ES2022) keeps the original error and the message says what exactly we were doing:

async function getBalance(accountId: string): Promise<number> {
  try {
    const res = await api.get('/accounts/' + accountId);
    return res.balance;
  } catch (err) {
    throw new Error('Failed to get balance for ' + accountId, { cause: err });
  }
}

The Playwright report shows the chain of causes, so such a message immediately shows both the step and the root source. For this lib must include ES2022 (with target: ES2022 it does).

What the person investigating a failure sees

Wrong

catch returns undefined

The failure comes on the next line: «Cannot read properties of undefined». The real cause, a 500 from the API, left no trace.

Right

Rethrow with cause

The report has the step («Failed to get balance for acc-1») and the root source (status and API response) in one chain.

Figure 1. An error must reach the report together with its cause instead of vanishing in a helper.

The error type in catch. Under strict (on by default since TypeScript 6.0) the variable in catch is unknown because anything can be thrown, not only an Error. Before touching fields it is narrowed:

try {
  await getBalance('acc-1');
} catch (err) {
  console.log(err.message);               // error: err is unknown
  if (err instanceof Error) {
    console.log(err.message, err.cause);  // ok, cause is unknown
  }
}

Negative tests. A manual try/catch in a test has a hole: if there is no error the catch branch does not run and the test passes. expect(promise).rejects fails the test when there is no error too:

// weak: if there is no error the test passes
try {
  await api.transfer({ amount: -100 });
} catch (e) {
  expect(String(e)).toMatch(/amount/i);
}

// reliable: no error fails the test as well
await expect(api.transfer({ amount: -100 })).rejects.toThrow(/amount/i);

Here it matters to pass the promise itself and not the result of a function that throws synchronously. If api.transfer is not declared async and throws before returning a promise, the error escapes before expect.

Playwright API tests and statuses.

const res = await request.post('/api/transfers', { data: { amount: -1 } });
expect(res.status()).toBe(400);          // a 4xx does not throw

const strict = await request.post('/api/transfers', {
  data: { amount: 10 },
  failOnStatusCode: true,                // throws on codes other than 2xx and 3xx
});
await expect(strict).toBeOK();

request.post() returns a response for any status by default, so the status is checked explicitly. The failOnStatusCode option makes it throw an error on codes other than 2xx and 3xx. Negative scenarios do not need it because a 4xx is expected there.

Limits and alternatives: finally and fixtures. finally guarantees cleanup, but in Playwright cleanup is better given to a fixture: the code after use() runs even when the test failed, and the test contains no try/finally of its own:

export const test = base.extend<{ account: Account }>({
  account: async ({ request }, use) => {
    const account = await createAccount(request);
    await use(account);
    await deleteAccount(request, account.id);   // runs even after the test failed
  },
});

An error in the cleanup itself must also be visible and not swallowed: otherwise garbage accumulates silently.

Common mistakes.

  • An empty catch or a catch with return undefined: a failure becomes a falsely green test or an unclear error further down.
  • A new error without cause: the original stack and the API response are lost.
  • Using err.message without narrowing: the compiler will not allow it under strict, and as Error only silences the problem.
  • A manual try/catch in a negative test without checking the success branch.
  • Expecting request.post() to throw on 4xx/5xx: by default it returns the response.

Check yourself

A test has try { await api.transfer({ amount: -100 }); } catch (e) { expect(String(e)).toMatch(/amount/) }. After a backend change transfer started returning 200. Will the test fail?

Answer

No. There is no error, the catch branch does not run, no check happens and the test is green. The bug (a negative amount accepted) slipped past. Use await expect(api.transfer(...)).rejects.toThrow(...): it fails also when there was no error.

Why pass { cause: err } to new Error(...) if the message already contains the account id?

Answer

The message says what we were doing and cause keeps why it failed: the original error with its stack, status or API response. Without it only our string remains and the root source has to be reproduced by hand.

In an interview. Junior: An error in async code is caught with try/catch around await. I do not swallow errors in helpers and I use expect(...).rejects in negative tests. Middle/Senior: In test code an error must reach the report with its true cause, so I rethrow with context and cause instead of returning undefined. The variable in catch is unknown and I narrow it. In Playwright request does not throw on 4xx/5xx, so I check the status explicitly, and I give cleanup to a fixture where code after use() runs even after the test failed.