Skip to content

JavaScript await keyword

  • by

The await keyword is used in JavaScript within an async function to pause the execution and wait for a Promise to settle. It allows you to write asynchronous code in a more synchronous-like manner, making it easier to handle and sequence asynchronous operations.

When used with await, a Promise is awaited, and the function’s execution is halted until the Promise resolves or rejects. Once the Promise settles, the function resumes its execution, and the resolved value (or the rejected value, which can be caught using a try...catch block) is available for further processing.

The await keyword is used in JavaScript within a async function to wait for a Promise to settle. The syntax for use await is as follows:

async function functionName() {
  // Asynchronous code

  // Wait for a Promise to settle
  const result = await promise;

  // Continue executing after the Promise settles
}

This enables more readable and structured code when dealing with asynchronous operations in JavaScript.

  1. Define a async function using the async keyword.
  2. Within the function, use the await keyword followed by a Promise. This can be any expression that resolves to a Promise, such as a function call that returns a Promise.
  3. The await expression pauses the execution of the async function until the Promise is settled (resolved or rejected).
  4. When the Promise is settled, the resolved value is assigned to the variable specified after the await keyword. In the example above, the resolved value is assigned to the result variable.
  5. The execution of the async function resumes after the await expression, allowing you to continue with the code that follows.

It’s important to note that await can only be used inside an async function. If you try to use it outside of a async function, it will result in a syntax error.

JavaScript await example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Await Example</title>
  <script>
    function delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function example() {
      console.log("Before delay");
      await delay(2000);
      console.log("After delay");
    }

    example();
  </script>
</head>
<body>
  <h1>JavaScript Await Example</h1>
  <p>Check the browser console for output.</p>
</body>
</html>

Output:

JavaScript await keyword

This demonstrates the execution flow of the async function and the usage of await within JavaScript code embedded in an HTML document.

Do comment if you have any doubts or suggestions on this JS keyword topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading