SyntaxStudy
Sign Up
JavaScript Intermediate 8 min read

async/await Basics

async/await Basics

The async/await syntax, introduced in ES2017, is syntactic sugar over promises. It allows you to write asynchronous code that reads like synchronous code, dramatically improving readability and reducing the mental overhead of chains of .then() calls.

async Functions

Declaring a function with the async keyword makes it return a promise automatically. Any value you return from an async function becomes the resolved value of that promise.

await

The await keyword can only be used inside async functions. It pauses execution of the function until the awaited promise settles, then unwraps the resolved value. Crucially, the rest of the JavaScript event loop continues to run while the function is paused.

Top-level await

In ES modules (and modern bundlers), await can be used at the top level of a module without wrapping it in an async function.

Example
async function fetchUser(id) {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/' + id);
  const user = await response.json();
  return user;
}
async function main() {
  const user = await fetchUser(1);
  console.log(user.name);
}
main();
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function sequence() {
  console.log('start');
  await delay(1000);
  console.log('after 1s');
  await delay(1000);
  console.log('after 2s');
}
sequence();
Pro Tip

An async function always returns a promise — even if you write return 42, the caller receives Promise.resolve(42). This means callers must use await or .then() to get the value.