typestar

Errors in async functions in JavaScript

await turns a rejection into a throw, so try/catch works again.

async function load(lang) {
  if (!lang) throw new RangeError("lang is required");
  return { lang, steps: 45 };
}

async function main() {
  try {
    console.log(await load("javascript"));
    await load("");
  } catch (error) {
    console.log(error.name, error.message);
  } finally {
    console.log("finished");
  }

  const settled = await load("go").catch(() => null);
  console.log(settled?.lang);

  const results = await Promise.allSettled([load("a"), load("")]);
  console.log(results.map((r) => r.status));
}

main();

How it works

  1. An async function always returns a promise.
  2. A throw inside it becomes a rejection.
  3. Forgetting await before a rejecting call loses the error.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
494
Tokens
155
Three-star pace
100 tpm

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

Type this snippet

Step 2 of 4 in async and await, step 7 of 19 in Promises & async.

← Previous Next →