Playwright + TS · Lesson 12 of 36

0/36 done

Module 12: Async TypeScript for Playwright

12. Mastering Async/Await for Automation Workflows

18 minlesson

Try it yourself

Implement an asynchronous test helper function waitForCondition:

  1. Repeatedly poll predicate() until it resolves to true.
  2. Throw an Error when timeoutMs expires.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Why Playwright is 100% Asynchronous

Browsers run out-of-process from Node.js. When your script executes page.click("#submit"), Node sends a WebSocket message to the browser, the browser scrolls, clicks, and sends a response back. Therefore, every Playwright operation returns Promise<void> or Promise<T>.


The Golden Rule: Never Forget await

typescript
// ❌ WRONG: page.click returns a Promise. Without await, Node fires and moves to the next line immediately!
page.click("button#login");
page.fill("input#code", "1234"); // Fails because page hasn't navigated or button click didn't finish!

// ✅ CORRECT:
await page.click("button#login");
await page.fill("input#code", "1234");

Sequential vs Parallel Execution in Automation

typescript
// Sequential: Task B relies on Task A
async function loginWorkflow() {
  await fillUsername();
  await fillPassword();
  await clickSubmit();
}

// Parallel: Tasks are completely independent (e.g., preparing two API preconditions)
async function prepareTestData() {
  const [userResponse, inventoryResponse] = await Promise.all([
    fetch("https://api.test/user"),
    fetch("https://api.test/inventory"),
  ]);
  return { userResponse, inventoryResponse };
}

Async Retry Utility Pattern

Automation tests occasionally encounter transient network delays. A strongly typed async retry function:

typescript
export async function retryOperation<T>(
  action: () => Promise<T>,
  retries: number = 3,
  delayMs: number = 1000
): Promise<T> {
  let lastError: unknown;
  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      return await action();
    } catch (err) {
      lastError = err;
      if (attempt < retries) {
        await new Promise((resolve) => setTimeout(resolve, delayMs));
      }
    }
  }
  throw lastError;
}

Key Takeaways & Walkthrough Summary

In Playwright, almost every single method returns a Promise. Missing an await keyword is the number one bug beginners encounter. In this lesson, we will master async and await specifically for Playwright workflows, exploring sequential steps, parallel test setups, and resilient async retry patterns. Let's dive in!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What happens if I forget 'await' on an expect assertion?

Web-first assertions like await expect(locator).toBeVisible() return a Promise. Omitting await means the assertion object is created but never evaluated, causing false-positive passes!

Can I use Array.prototype.forEach with async/await?

No! forEach does NOT await async callbacks. Always use a standard 'for...of' loop or 'await Promise.all(items.map(async ...))'.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip