Skip to content
Kuza Ndoto Academy

Async & Await

Beginner → IntermediateChapter 5 · Page 24 of 324 min readUpdated 15 Nov 2026

async and await let you write promise-based code that reads from top to bottom, like ordinary step-by-step code. Under the hood they still use promises, but you lose the long .then chains and can handle errors with familiar try/catch.

async functions

Putting async before a function changes two things: the function always returns a promise, and you may use await inside it. A normal return value is wrapped in a fulfilled promise; a thrown error becomes a rejected one.

async function getNumber() {
  return 7;
}

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

The arrow-function form is const getNumber = async () => 7;, and methods can be async too.

await

await promise pauses the async function until the promise settles, then gives you its value. Only that function pauses: the rest of the page, and code outside the function, keeps running.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function makeChai() {
  console.log("Boiling water...");
  await wait(1000);
  console.log("Adding tea leaves...");
  await wait(500);
  return "Chai is ready";
}

makeChai().then((message) => console.log(message));
console.log("Meanwhile, setting the table");
Boiling water... Meanwhile, setting the table Adding tea leaves... Chai is ready

The function runs normally until its first await. There it pauses and hands control back, so "Meanwhile, setting the table" logs second. When the promise fulfils, the rest of the function continues as a microtask (see the event loop).

Promise chain async / await getUser() .then((user) => getOrders(user)) .then((orders) => show(orders)) .catch(handleError) try { const user = await getUser(); const orders = await getOrders(user); show(orders); } catch (error) { handleError(error); }
Figure 1. Two ways to write the same three steps. Both use the same promises; await simply lets you read them top to bottom, and catch handles a failure at any step.

Handling errors with try/catch

If an awaited promise rejects, await throws the rejection reason as an error at that line. Catch it with try/catch, exactly like a synchronous error, and use finally for clean-up.

function payFees(amount) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (amount > 0) resolve(`Paid KES ${amount}`);
      else reject(new Error("Amount must be positive"));
    }, 300);
  });
}

async function run() {
  try {
    console.log(await payFees(2500));
    console.log(await payFees(0));
    console.log("not reached");
  } catch (error) {
    console.log("Error:", error.message);
  } finally {
    console.log("Receipt printed");
  }
}

run();
Paid KES 2500 Error: Amount must be positive Receipt printed

You can also handle the error where you call the function: run().catch(...). Remember that an async function's errors become a rejected promise, so somebody must catch them. More on this in Error Handling.

Sequential or parallel?

Each await waits for the previous one. That is right when a step needs the result of the one before it, but wasteful when the jobs are independent.

const after = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function sequential() {
  const start = Date.now();
  const a = await after(1000, "maize");
  const b = await after(1000, "beans");
  console.log(a, b, Date.now() - start);
}

async function parallel() {
  const start = Date.now();
  const [a, b] = await Promise.all([after(1000, "maize"), after(1000, "beans")]);
  console.log(a, b, Date.now() - start);
}

Calling sequential() takes about two seconds; calling parallel() takes about one, because both timers run at the same time (the exact milliseconds will be slightly higher on your machine):

maize beans 2000 maize beans 1000

await in loops

To process items one after another, use for...of with await inside an async function. Don't use forEach: it ignores the promises your callback returns and doesn't wait.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function remindAll(names) {
  for (const person of names) {
    await wait(200);
    console.log("SMS sent to", person);
  }
  console.log("All reminders sent");
}

remindAll(["Amina", "Baraka"]);
SMS sent to Amina SMS sent to Baraka All reminders sent

With names.forEach(async (person) => {...}) instead, "All reminders sent" would log first, before any SMS.

Common mistake

Forgetting await. const data = getData(); gives you a pending promise, not the data, so data.name is undefined. The opposite mistake, using await inside a function that isn't async, is a SyntaxError. (In ES modules you may also use await at the top level of the file.)

Key points

  • An async function always returns a promise; await pauses it until a promise settles.
  • Only the async function pauses; other code and the page keep running.
  • A rejected promise makes await throw, so wrap awaits in try/catch/finally.
  • Use Promise.all for independent jobs and for...of (not forEach) for one-at-a-time loops.
Up next · Asynchronous JavaScriptFetch & APIsRequest data from web APIs.
→

Tip: use the ← and → keys to move between pages.