JavaScript Tutorial · Asynchronous JavaScript · Lesson 33 of 44

JavaScript Async/Await

Write asynchronous code that reads like synchronous code.

async functions

An async function always returns a promise. Inside it, await pauses until a promise settles and gives you its value — no .then() chains:

Example 1Try it yourself
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function loadProfile() {
  console.log("loading...");
  await wait(100);
  return { name: "Ada", plan: "pro" };
}

const profile = await loadProfile();
console.log(profile);

Output

loading...
{ name: 'Ada', plan: 'pro' }

Error handling

A rejected promise makes await throw, so use ordinary try...catch:

Example 2Try it yourself
async function fetchPrice(symbol) {
  if (symbol !== "ACME") throw new Error(`Unknown symbol ${symbol}`);
  return 42;
}

async function main() {
  try {
    console.log(await fetchPrice("ACME"));
    console.log(await fetchPrice("NOPE"));
  } catch (err) {
    console.log("Error:", err.message);
  } finally {
    console.log("finished");
  }
}
await main();

Output

42
Error: Unknown symbol NOPE
finished

Sequential vs parallel

await in a loop runs tasks one after another. When tasks are independent, start them all and await Promise.all(...) — much faster:

Example 3Try it yourself
const task = (name, ms) => new Promise((resolve) => setTimeout(() => resolve(name), ms));

let start = Date.now();
for (const [name, ms] of [["a", 100], ["b", 100], ["c", 100]]) {
  await task(name, ms);
}
console.log("sequential ≈", Math.round((Date.now() - start) / 100) * 100, "ms");

start = Date.now();
const results = await Promise.all([task("a", 100), task("b", 100), task("c", 100)]);
console.log(results, "parallel ≈", Math.round((Date.now() - start) / 100) * 100, "ms");

Output

sequential ≈ 300 ms
[ 'a', 'b', 'c' ] parallel ≈ 100 ms

Test yourself

What does an async function always return?

  1. A Promise
  2. undefined
  3. A callback
  4. The awaited value
Show answer

Answer: A Promise

Practice next