typestar

async and await in JavaScript

Writing asynchronous code that reads sequentially.

async function loadUser(id) {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new Error(`status ${response.status}`);
  }
  return response.json();
}

async function main() {
  try {
    const user = await loadUser(7);
    console.log(user.name);
  } catch (error) {
    console.error(error.message);
  }
}

How it works

  1. await pauses until the promise settles.
  2. A non-ok response is turned into a thrown error.
  3. try/catch handles rejections like normal errors.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
312
Tokens
95
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 1 of 4 in async and await, step 6 of 19 in Promises & async.

← Previous Next →

async and await in other languages