async / await

Topic 4 of 5 in Asynchronous code6 min readBeginnerFree course

Overview

async and await are a nicer way to work with promises. Your code reads top to bottom, but it still doesn’t block the page.

JavaScript
async function showCourses() {
  const response = await fetch('/api/courses');
  const courses = await response.json();
  console.log(courses);
}

Compare it with the same thing as a promise chain:

JavaScript
function showCourses() {
  return fetch('/api/courses')
    .then((response) => response.json())
    .then((courses) => console.log(courses));
}

They do exactly the same thing. The async version just lets you name each intermediate value and write the steps as normal statements.

How it works

Marking a function async makes it return a promise. Inside it, await waits for a promise to settle and gives you its value.

JavaScript
async function getNumber() {
  return 42;
}

getNumber();                         // Promise {<fulfilled>: 42}
getNumber().then((n) => console.log(n)); // 42

When the function hits await, it pauses and hands control back to the event loop. Other code — clicks, timers, other functions — keeps running. When the promise settles, the function carries on from where it stopped.

JavaScript
async function demo() {
  console.log('2. before await');
  await wait(1000);
  console.log('4. after await');
}

console.log('1. start');
demo();
console.log('3. demo is paused, but this runs');

await only pauses the async function it’s in — never the whole program.

Calling an async function

Because it returns a promise, the caller either awaits it (inside another async function) or uses .then():

JavaScript
const courses = await loadCourses(); // inside an async function or module

loadCourses().then(render);          // anywhere

Forgetting await is a common mistake — you get a pending promise instead of the data:

JavaScript
const courses = loadCourses(); // Promise, not an array!
courses.length;                // undefined

Handling errors

A rejected promise throws at the await, so you can use a normal try / catch:

JavaScript
async function showCourses() {
  try {
    const response = await fetch('/api/courses');
    console.log(await response.json());
  } catch (error) {
    console.error('Could not load courses', error);
  } finally {
    hideSpinner();
  }
}

If you don’t catch inside, the error rejects the promise the function returns, so the caller can handle it instead. Decide which level is best placed to deal with it.

Running things in parallel

await one after another runs steps in sequence. To start several at once, use Promise.all:

JavaScript
const [user, courses] = await Promise.all([loadUser(), loadCourses()]);

Sequential: await loadUser (800 ms) then await loadCourses (1000 ms) takes 1.8 seconds. Parallel: await Promise.all([loadUser(), loadCourses()]) runs both at once and takes 1.0 second.

Only go sequential when a step needs the previous result — for example, loading a user’s courses needs the user’s id first. Otherwise, start everything together.

JavaScript
// Sequential — needed: the second call uses the first result
const user = await loadUser();
const courses = await loadCoursesFor(user.id);

// Parallel — independent requests
const [news, weather] = await Promise.all([loadNews(), loadWeather()]);

Use Promise.allSettled if you want every result even when some fail.

Loops

await works naturally in for…of, running one iteration at a time:

JavaScript
for (const id of ids) {
  const course = await loadCourse(id); // one after another
  render(course);
}

But forEach does not wait for async callbacks — it fires them all and moves on:

JavaScript
ids.forEach(async (id) => {
  await save(id); // these all start at once; forEach doesn't wait
});
console.log('done?'); // runs before any save finishes

To process items in parallel and wait for all of them, combine map with Promise.all:

JavaScript
const courses = await Promise.all(ids.map((id) => loadCourse(id)));

Async arrow functions and methods

JavaScript
const load = async (url) => (await fetch(url)).json();

class Api {
  async get(path) {
    const res = await fetch(`/api${path}`);
    return res.json();
  }
}

button.addEventListener('click', async () => {
  const data = await load('/api/data');
  render(data);
});

await only works inside async functions — or at the top level of a JavaScript module.

Summary: three ways to write the same thing

JavaScript
// Callbacks
loadUser(id, (err, user) => { if (err) return showError(err); render(user); });

// Promises
loadUser(id).then(render).catch(showError);

// async / await
try {
  render(await loadUser(id));
} catch (err) {
  showError(err);
}
Exercise

Convert to async / await

Rewrite this promise chain as an async function with try / catch. Then write loadBoth() that loads courses and the user in parallel.

JavaScript
function loadCourses() {
  return fetch('/api/courses')
    .then((res) => res.json())
    .catch(() => []);
}

function loadUser() {
  return fetch('/api/user').then((res) => res.json());
}

Summary

  • async functions always return a promise.
  • await pauses only that function until a promise settles, then gives you its value.
  • Use try / catch around await to handle errors.
  • Independent steps should run in parallel with Promise.all, not one await after another.
  • Use for…of (not forEach) when you need to await inside a loop.