Asynchronous code: promises and async/await

Why Node.js is asynchronous, and how to write async code that's easy to read and doesn't block.

Module 2: JavaScript on the server · Lesson 4 of 26 · 18 min read · Free

A back end spends most of its time waiting — for the database, for another API, for a file. If it stopped everything while waiting, one slow request would make every other customer wait. Node.js doesn't: while one request waits, it serves others.

Blocking versus asynchronous

Promises

An async operation returns a promise: an object that will later contain a result (fulfilled) or an error (rejected). Simulate a slow database call and run it:

function getOrder(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 1) resolve({ id: 1, customer: "Tolu Bello", total: 10500 });
      else reject(new Error(`Order ${id} not found`));
    }, 500);
  });
}

async function main() {
  console.log("Looking up order 1…");
  const order = await getOrder(1);           // waits here, without blocking anything else
  console.log("Found:", order.customer, order.total);

  try {
    await getOrder(99);
  } catch (err) {
    console.error("Error:", err.message);    // rejected promises become exceptions
  }
}
main();

async / await rules

  • await waits for a promise; it can only be used in an async function (or at the top level of an ES module).
  • An async function always returns a promise.
  • Wrap awaited code in try / catch to handle failures.

Doing things in parallel

Awaiting one after another is slow when the tasks don't depend on each other:

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

async function main() {
  let t = Date.now();
  const a = await wait(400, "menu");
  const b = await wait(400, "user");
  console.log("One after the other:", Date.now() - t, "ms");

  t = Date.now();
  const [menu, user] = await Promise.all([wait(400, "menu"), wait(400, "user")]);
  console.log("In parallel:", Date.now() - t, "ms", menu, user);
}
main();

Promise.all runs them together and waits for all of them — about half the time here.

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. What does an async function always return?

    • A A promise
    • B A string
    • C undefined
    • D An array
    Show the answer

    A) A promise — Even if you return a value, it's wrapped in a promise.

  2. How do you handle a rejected promise when using await?

    • A Wrap it in try/catch
    • B Use if/else
    • C It can't be handled
    • D Add a second await
    Show the answer

    A) Wrap it in try/catch — await turns rejections into exceptions.

  3. Two independent database calls each take 400 ms. How can you run them in about 400 ms total?

    • A await Promise.all([callA(), callB()])
    • B await callA(); await callB();
    • C Use a for loop
    • D Remove await
    Show the answer

    A) await Promise.all([callA(), callB()]) — Promise.all runs them concurrently.

More free lessons: What the back end does · Install Node.js and use the terminal · HTTP: requests, responses and status codes · Designing a REST API · Designing tables and relationships · Storing passwords safely · Automated tests and project structure