await Keyword

Introduction

The await keyword is used inside an async function to pause the execution of that function until a Promise is settled. Once the Promise is fulfilled, await returns the resolved value. If the Promise is rejected, an error is thrown, which can be handled using try...catch.

The await keyword makes asynchronous code look and behave like synchronous code, making it much easier to understand than long Promise chains.

In Node.js, await is widely used for reading files, making API requests, querying databases, browser automation, and interacting with cloud services.

For automation engineers, await is one of the most frequently used JavaScript features because frameworks like Playwright, Puppeteer, WebdriverIO, and many modern Node.js libraries rely heavily on asynchronous operations.

In this tutorial, you’ll learn how the await keyword works and how to use it effectively.


What is the await Keyword?

The await keyword pauses the execution of an async function until a Promise is fulfilled or rejected.

After the Promise is resolved, execution continues with the resolved value.


Why Use the await Keyword?

The await keyword helps developers:

  • Write cleaner asynchronous code.

  • Improve code readability.

  • Avoid long Promise chains.

  • Simplify asynchronous workflows.

  • Handle asynchronous operations sequentially.

  • Improve debugging.

  • Write code that is easier to maintain.


Syntax

async function example() {

    const result =

        await promise;

}

Example 1: Basic await

async function greet() {

    const message =

        await Promise.resolve(

            "Hello World"

        );

    console.log(message);

}

greet();

Sample Output

Hello World

Example 2: Waiting for a Number

async function getNumber() {

    const number =

        await Promise.resolve(100);

    console.log(number);

}

getNumber();

Sample Output

100

Example 3: Waiting for an Object

async function getUser() {

    const user =

        await Promise.resolve({

            name: "Rahul",

            city: "Delhi"

        });

    console.log(user);

}

getUser();

Sample Output

{ name: 'Rahul', city: 'Delhi' }

Example 4: Using await with setTimeout()

function delay() {

    return new Promise(function (resolve) {

        setTimeout(function () {

            resolve(

                "Task completed."

            );

        }, 2000);

    });

}

async function runTask() {

    const result =

        await delay();

    console.log(result);

}

runTask();

Sample Output

Task completed.

Example 5: Sequential Execution

async function executeTasks() {

    const first =

        await Promise.resolve(

            "Step 1"

        );

    console.log(first);

    const second =

        await Promise.resolve(

            "Step 2"

        );

    console.log(second);

}

executeTasks();

Sample Output

Step 1
Step 2

Automation Testing Examples

The await keyword is extensively used in automation frameworks to execute asynchronous tasks in sequence.

Playwright Example

Wait for an application to load.

async function openApplication() {

    const message =

        await Promise.resolve(

            "Application loaded."

        );

    console.log(message);

}

openApplication();

Sample Output

Application loaded.

Selenium Example

Wait for the browser to launch.

async function launchBrowser() {

    const message =

        await Promise.resolve(

            "Browser launched."

        );

    console.log(message);

}

launchBrowser();

Sample Output

Browser launched.

Cypress Example

Wait for a page to load.

async function visitPage() {

    const message =

        await Promise.resolve(

            "Page loaded."

        );

    console.log(message);

}

visitPage();

Sample Output

Page loaded.

API Testing Example

Wait for an API response.

async function fetchApi() {

    const response =

        await Promise.resolve(

            "API response received."

        );

    console.log(response);

}

fetchApi();

Sample Output

API response received.

Data-Driven Testing Example

Wait for CSV data to load.

async function loadCsv() {

    const data =

        await Promise.resolve(

            "CSV data loaded."

        );

    console.log(data);

}

loadCsv();

Sample Output

CSV data loaded.

Common Uses of the await Keyword

The await keyword is commonly used for:

  • Reading files.

  • Writing files.

  • API requests.

  • Database queries.

  • Browser automation.

  • User authentication.

  • Processing JSON data.

  • Uploading files.

  • Report generation.

  • Workflow automation.


Common Mistakes

Using await Outside an async Function

Incorrect:

const result =

    await Promise.resolve(10);

Correct:

async function example() {

    const result =

        await Promise.resolve(10);

}

Forgetting Error Handling

Always use try...catch when awaiting Promises that may fail.


Waiting for Independent Tasks Sequentially

If multiple tasks are independent, use Promise.all() instead of awaiting each one individually to improve performance.


Best Practices

  • Use await only inside async functions.

  • Handle errors using try...catch.

  • Use Promise.all() for independent asynchronous tasks.

  • Keep asynchronous functions simple.

  • Use descriptive function names.

  • Avoid unnecessary await statements.

  • Write readable asynchronous code.


Conclusion

The await keyword makes asynchronous programming significantly easier by allowing developers to write code that looks and behaves like synchronous code. It removes the complexity of Promise chains while improving readability and maintainability.

For automation engineers, await is one of the most important JavaScript features because nearly every browser action, API request, file operation, and database interaction in modern automation frameworks is asynchronous. Mastering the await keyword is essential for writing efficient and professional Node.js automation scripts.


Frequently Asked Questions (FAQs)

What does the await keyword do?

It pauses the execution of an async function until a Promise is fulfilled or rejected.


Can I use await outside an async function?

No. The await keyword can only be used inside an async function (except for supported top-level await in ES modules).


Does await block the entire program?

No. It pauses only the current async function. Other JavaScript code can continue running.


Should I use await or .then()?

Both work, but await is generally preferred because it produces cleaner and more readable code.


Why is await important in automation testing?

Automation frameworks perform many asynchronous operations, such as clicking buttons, waiting for elements, reading files, and making API requests. The await keyword simplifies these operations.


Key Takeaways

  • await pauses an async function until a Promise settles.

  • It can only be used inside an async function (except supported top-level await).

  • It returns the resolved value of a Promise.

  • Rejected Promises throw errors that can be handled with try...catch.

  • await makes asynchronous code easier to read.

  • It reduces the need for complex Promise chains.

  • Use Promise.all() for independent concurrent tasks.

  • Modern Node.js applications heavily rely on await.

  • Automation frameworks use await extensively.

  • Mastering await is essential for writing clean and maintainable asynchronous JavaScript.