Why do we write await/async in Playwright Javascript/Typescript?

Jadala Ajay
2 min readFeb 4, 2023

--

Sample test in playwright:

import { test, expect } from '@playwright/test';

test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
await expect(page).toHaveTitle(/Playwright/);
});

We need these two keywords in Playwright to write our test because any tool based on node js is asynchronous.

What does asynchronous mean?
Synchronous : your program will execute the second line once the first line is executed successfully.
Asynchronous: your second line can execute even before the first line.

To resolve promises on each statement we write await. When we write await, we have to mark the function with async=>().

What is a promise?
A promise is an object returned by an asynchronous function, which represents the current state of the operation.

How does async/wait solve asynchronous?
The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment, which means the second line of code waits till the first line of code executes completely.

  1. What happens when we remove async (keeping await in the statements)?
    you will get a syntax error that “await is only valid in async functions and the top-level bodies of modules.”
  2. What happens if you remove await in front of page.goto(‘https://playwright.dev/') for above test?
    We get an error saying “Navigation failed because page was closed!”.

Note: we need to keep await only when we are performing some action.See below example

const userName = page.locator('#username'); //no need to use await here
await page.locator("#okayBtn").click();// we must use await here since we are doing some action.

Another example of keeping await outside/inside expect function.

1. await expect(page.locator(".radiotextsty").last()).toBeChecked();//here we are doing action outside so we kept await outside expect.
2. expect( await page.locator("#terms").isChecked()).toBeFalsy();//here we are doing action inside so kept await inside expect.

This is how JavaScript-based test automation handles asynchronous code in test automation with the help of the async/await technique.

Hope you enjoyed this article !! See you in other posts. Please comment if you have any thoughts on this. Please share whomever this may be useful.

--

--

Jadala Ajay

8 Years Exp Senior Automation Engineer with expertise on Selenium,RestAsured API,Postman,Cypress,WebdriverIO with prog languages Java,Javascript and Python