Dmytro Morar
JavaScript

Async Await

Async / Await is syntactic sugar over promises that makes asynchronous code readable and linear, while maintaining the benefits of Promise and the Event Loop.

Main Idea

  • async and await simplify working with promises, allowing you to write asynchronous code in a synchronous style.
  • The async keyword before a function automatically makes it return a Promise.
  • The await keyword pauses function execution until the promise is settled (fulfilled or rejected).

How It Works

async function getUserData() {
  try {
    const response = await fetch('/api/user');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}
  • await can be used only inside an async function.
  • When await promise is executed, the interpreter pauses the function, releasing the thread for other tasks (via the Event Loop).
  • After the promise is resolved, execution continues with the received value.
  • If the promise was rejected, an exception is generated, which can be caught via try...catch.

Behavior and Microtasks

  • Every await access creates a microtask.
  • After pausing the function, the execution of other microtasks continues until the promise is completed.
  • async/await does not block the thread — it simply splits execution into phases.
  • If there is an error in await, it is passed to the nearest catch.

Sequential and Parallel Calls

Sequential execution (slower):

await fetchData1();
await fetchData2();
await fetchData3();

Parallel execution (more optimal):

const [a, b, c] = await Promise.all([fetchData1(), fetchData2(), fetchData3()]);

Key Ideas

  • async guarantees that the function always returns a Promise.
  • await makes the code readable and step-by-step, simplifying the handling of asynchronous operations.
  • Allows using try...catch instead of .then() / .catch().
  • Behind the scenes is the same mechanism of promises and the microtask queue of the Event Loop.
  • Combined with Promise.all and Promise.allSettled for optimizing parallel operations.

On this page