Playwright + TS · Lesson 12 of 36
Module 12: Async TypeScript for Playwright
Try it yourself
Implement an asynchronous test helper function waitForCondition:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
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>.
await// ❌ 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: 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 };
}Automation tests occasionally encounter transient network delays. A strongly typed async retry function:
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;
}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.
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!
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.