23 Feb 2024




Intermediate

Async/await is a powerful feature introduced in ECMAScript 2017 (ES8) for managing asynchronous code in JavaScript. It provides a more concise and readable syntax for working with promises and asynchronous operations. Async/await is built on top of promises and makes asynchronous code look more like synchronous code, which is easier to understand and maintain.

  • Async Functions: The async keyword is used to define asynchronous functions. An async function returns a promise implicitly, which resolves with the value returned by the async function, or rejects with an exception thrown from the async function.

  • Await Expression: The await keyword is used to pause the execution of an async function until a promise is settled (either resolved or rejected). It can only be used inside an async function.

Eexample:

async function fetchData() {
    // This fetch call returns a Promise
    let response = await fetch('https://api.example.com/data');
    // The execution pauses here until the promise is resolved

    // Once the promise is resolved, we can extract JSON from the response
    let data = await response.json();
    // Again, the execution pauses here until the promise is resolved

    // Now we can work with the data
    console.log(data);
}

// Call the async function
fetchData();

In this example, fetchData() is an async function that fetches data from an API endpoint. The await keyword is used to wait for the fetch operation and the response.json() operation to complete before proceeding further. This makes the asynchronous code appear synchronous, which can improve readability and maintainability.

javascript
async
await