Skip to main content
← ⚑ JavaScript & the browserΒ·Module C4 Β· Lesson 2
TaskWrite async function double(n) that returns a Promise resolving to n*2 (use await on Promise.resolve(n*2)). Call it once with 7, log the awaited result.

JavaScript async / await Tutorial: Promise chains, simplified

100 XP7 min
Theory

Two syntaxes, one thing

// .then chain
function load() {
  return fetch("/api/user")
    .then(r => r.json())
    .then(user => user.name);
}

// async / await
async function load() {
  const r = await fetch("/api/user");
  const user = await r.json();
  return user.name;
}

Both functions return a Promise. Both wait for fetch and json. The async version reads like synchronous code, which is why it won the syntax war.

Two rules

  1. await can only appear inside an async function (or at the top level of a module β€” C4-09).
  2. async functions always return a Promise. Even async function x() { return 5; } returns Promise<5>, not 5.

try / catch for errors

async function load() {
  try {
    const r = await fetch("/api/user");
    if (!r.ok) throw new Error(\`HTTP ${r.status}\`);
    return await r.json();
  } catch (err) {
    console.error("load failed:", err);
    return null;
  }
}

try/catch around await catches both network errors (the fetch threw) and your manual throws (the bad-status throw). That's the whole error model.

Don't forget to await

async function bad() {
  fetch("/api/log");        // fire and forget β€” error swallowed, ordering unclear
}

async function good() {
  await fetch("/api/log");  // sequential, errors propagate
}

Forgetting await is the #1 async bug. The function continues immediately without waiting; errors disappear into the void. Lint rules can flag this.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.