async
await
order of execution
JavaScript
asynchronous programming

order of execution in async/await

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Understanding the Order of Execution with `async/await` in JavaScript

The `async/await` pattern is a syntactic sugar built on top of Promises in JavaScript that allows developers to write asynchronous code more comfortably and readably. However, despite the simplicity `async/await` brings, understanding its order of execution requires a solid grasp of how it interacts with the JavaScript event loop and promises. Here, we delve into the technicalities of `async/await` execution order.

Basic Concepts

Before diving into the details, let's quickly recap:

  • Promises: A promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation.
  • Async Function: Defined with the `async` keyword, it returns a promise and allows the usage of `await`.
  • Await Operator: Used before a promise, causing the `async` function to pause until the promise is fulfilled or rejected.

Technical Explanation

When you use `async/await`, the code is still asynchronous; it’s essentially a more readable way to work with promises. Here's a breakdown of how execution proceeds in an `async` function:

  1. Encounter an Async Function:
    • When JavaScript execution encounters an `async` function, it immediately returns a promise. The function execution continues until it hits the first `await` keyword.
  2. Awaiting a Promise:
    • Upon encountering `await`, the function's execution is paused (`yielded`) at this point until the promise resolves or rejects.
    • Meanwhile, the JavaScript engine moves on to execute other code in the call stack.
  3. Handling Promises with Await:
    • Once the promised value is ready — either resolved or rejected — execution resumes in the `async` function, continuing immediately after the `await`.
  4. Error Handling:
    • A promise rejected with `await` can be caught using traditional `try-catch` blocks within an `async` function.

Below is a simple example illustrating these steps:

  • The console will log `Fetching data...`.
  • It will then hit `await fetch` and pause the function at that point.
  • `After fetchData` will be logged next since the rest of the code runs independently of the async function.
  • Once the fetch promise resolves, `Data fetched` follows, then `Data processed`, and finally the `then` callback logs the fetched data.
  • When the `await` is hit, the promise is placed in the microtask queue. This queue is part of the event loop, and tasks in it are processed after the current script and before any other queued callback.

Course illustration
Course illustration

All Rights Reserved.