JavaScript – Promises and async/await

By Published 7 min read

JavaScript - Promises and async/await

Introduction:

JavaScript runs your code on a single thread: it can only do one thing at a time. Yet web pages load data from servers, wait for timers, read files and respond to clicks, all without freezing. The secret is asynchronous code: JavaScript starts a slow task, carries on with other work, and comes back to handle the result when it is ready.

Think of ordering coffee at a café. You order, get a receipt, and go read a book. When the coffee is ready, they call your name. You don’t stand frozen at the counter.

console.log("1. Order a coffee");
setTimeout(() => console.log("3. Coffee is ready"), 1000);
console.log("2. Read a book while waiting");

// 1. Order a coffee
// 2. Read a book while waiting
// 3. Coffee is ready

In the JavaScript Functions and Events lessons we passed functions to be called later. In this lesson we will see how asynchronous code evolved from callbacks to Promises to async/await, which is how modern JavaScript is written today.

The Problem with Callbacks

The oldest way to handle async results is a callback: a function you pass in, which is called when the work is done. Node.js style callbacks take an error as the first argument.

Now imagine three steps that depend on each other: load a user, then their orders, then the invoice for the first order.

getUser(1, (err, user) => {
  if (err) return console.error(err);
  getOrders(user, (err, orders) => {
    if (err) return console.error(err);
    getInvoice(orders[0], (err, invoice) => {
      if (err) return console.error(err);
      console.log(invoice); // { orderId: 7, paid: true }
    });
  });
});

Each step goes one level deeper, and every level must handle its own errors. With more steps this becomes the famous callback hell (or “pyramid of doom”): hard to read, easy to get wrong, and painful to change.

What Is a Promise?

A Promise is an object that represents a value that will be available later: like the receipt you get at the café. A Promise is always in one of three states:

  • Pending: the work is still going on.
  • Fulfilled: the work finished successfully, and the Promise has a value.
  • Rejected: the work failed, and the Promise has a reason (usually an Error).

Once a Promise is fulfilled or rejected, it is settled and never changes again.

1. Creating a Promise:

You create a Promise with new Promise, passing a function that receives two functions: resolve (call it with the result) and reject (call it with an error).

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id <= 0) reject(new Error("Invalid user id"));
      else resolve({ id, name: "Sara" });
    }, 100);
  });
}

In practice you will create Promises yourself only occasionally, usually to wrap old callback-based code. Most of the time you use Promises returned by APIs such as fetch.

A useful small helper that turns setTimeout into a Promise:

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

2. Using a Promise: then, catch and finally:

  • .then(fn) runs when the Promise is fulfilled and receives the value.
  • .catch(fn) runs when it is rejected and receives the error.
  • .finally(fn) runs in both cases, which is good for cleanup such as hiding a loading spinner.
getUser(0)
  .then((user) => console.log(user))
  .catch((err) => console.log("Caught:", err.message));

// Caught: Invalid user id

3. Chaining:

The real power of .then() is that it returns a new Promise. If your function returns a value or another Promise, the next .then() receives its result. This flattens callback hell into a straight line:

getUser(1)
  .then((user) => getOrders(user))
  .then((orders) => getInvoice(orders[0]))
  .then((invoice) => console.log(invoice))
  .catch((err) => console.error("Something failed:", err.message))
  .finally(() => console.log("done"));

// { orderId: 7, paid: true }
// done

One .catch() at the end handles an error from any step in the chain. Compare that with three separate if (err) checks in the callback version.

async and await

Promise chains are much better than callbacks, but async/await, added in ES2017, makes async code read almost like normal, step-by-step code.

  • Put async before a function. An async function always returns a Promise.
  • Inside it, put await before a Promise. The function pauses at that line until the Promise settles, then continues with its value. While it is paused, the rest of your program keeps running.
  • Handle errors with an ordinary try...catch.
async function showInvoice(userId) {
  try {
    const user = await getUser(userId);
    const orders = await getOrders(user);
    const invoice = await getInvoice(orders[0]);
    console.log(invoice);
    return invoice;
  } catch (err) {
    console.log("Error:", err.message);
  } finally {
    console.log("done");
  }
}

showInvoice(1);   // { orderId: 7, paid: true }  then  done
showInvoice(-1);  // Error: Invalid user id      then  done

This does exactly the same as the chain above, but it reads from top to bottom, and you can use normal if, loops and variables between the steps.

Remember that an async function returns a Promise, even when you return a plain value:

async function hello() {
  return "hi";
}

console.log(hello());      // Promise { 'hi' }
hello().then(console.log); // hi

A Real Example: fetch

The browser’s fetch function (also built into Node.js 18 and later) returns a Promise, so it works naturally with await. One important detail: fetch only rejects on network errors. An HTTP error such as 404 or 500 still fulfills the Promise, so you must check response.ok yourself.

async function loadUser(id) {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json(); // also returns a Promise
}

try {
  const user = await loadUser(1);
  console.log(user); // { id: 1, name: 'Sara' }
  await loadUser(2);
} catch (err) {
  console.log(err.message); // Request failed with status 404
}

(Using await outside a function, as in the last block, works in ES modules and the browser console. In a regular script, put it inside an async function.)

Running Tasks in Parallel

await waits for each Promise before starting the next line. That is what you want when a step depends on the previous one. But if the tasks are independent, waiting for each one in turn wastes time:

async function sequential() {
  const a = await wait(300, "profile");
  const b = await wait(300, "orders");
  const c = await wait(300, "reviews");
  return [a, b, c];
}
// sequential: about 900 ms

(Here wait(ms, value) is a version of our helper that resolves with value after ms milliseconds.)

Start all of them at once and wait for them together with Promise.all:

async function parallel() {
  const [a, b, c] = await Promise.all([
    wait(300, "profile"),
    wait(300, "orders"),
    wait(300, "reviews"),
  ]);
  return [a, b, c];
}
// parallel: about 300 ms, three times faster

JavaScript has four tools for combining Promises:

1. Promise.all:

Waits for all Promises and returns their values in the same order. If any of them rejects, Promise.all rejects immediately with that error.

try {
  await Promise.all([wait(100, "ok"), fail(50, "orders service down")]);
} catch (e) {
  console.log(e.message); // orders service down
}

2. Promise.allSettled:

Waits for all of them, whether they succeed or fail, and tells you what happened to each one. Use it when one failure shouldn’t throw away the other results, such as a dashboard loading several independent widgets.

const results = await Promise.allSettled([wait(100, "ok"), fail(50, "orders service down")]);
console.log(results.map((r) => (r.status === "fulfilled" ? r.value : r.reason.message)));
// [ 'ok', 'orders service down' ]

3. Promise.race:

Settles as soon as the first Promise settles, whether it succeeds or fails.

console.log(await Promise.race([wait(200, "slow server"), wait(100, "fast server")]));
// fast server

A classic use is adding a timeout to any Promise:

function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms)
  );
  return Promise.race([promise, timeout]);
}

try {
  await withTimeout(wait(1000, "data"), 200);
} catch (e) {
  console.log(e.message); // Timed out after 200 ms
}

4. Promise.any:

Fulfills with the first successful result and ignores failures (it rejects only if all of them fail). Useful for trying several mirrors or servers and using whichever answers first.

console.log(await Promise.any([fail(50, "mirror 1 down"), wait(150, "mirror 2"), wait(250, "mirror 3")]));
// mirror 2

How It Works: The Microtask Queue

When a Promise settles, its .then() callback (or the rest of an async function after await) is not run immediately. It is put in a queue called the microtask queue, which JavaScript empties as soon as the current code finishes, before timers such as setTimeout. That’s why this prints in a surprising order:

console.log("A");
setTimeout(() => console.log("B (timeout)"), 0);
Promise.resolve().then(() => console.log("C (promise)"));
console.log("D");

// A
// D
// C (promise)
// B (timeout)

We will look at this in much more detail in a later lesson about the JavaScript event loop.

Common Mistakes

1. Forgetting await:

Without await you get the Promise itself, not its value: const user = getUser(1) gives Promise { <pending> }, and user.name is undefined.

2. Using await inside forEach:

forEach does not wait for async callbacks. The code after it runs before any of them finish:

const ids = [1, 2, 3];

const out1 = [];
ids.forEach(async (id) => { out1.push(await wait(50, id * 10)); });
console.log(out1); // []  <- nothing yet!

const out2 = [];
for (const id of ids) out2.push(await wait(50, id * 10)); // one after another
console.log(out2); // [ 10, 20, 30 ]

console.log(await Promise.all(ids.map((id) => wait(50, id * 10)))); // all at once
// [ 10, 20, 30 ]

Use for...of when the steps must run in order, and Promise.all with map when they can run in parallel.

3. Not handling errors:

A rejected Promise with no .catch() or try...catch causes an “unhandled promise rejection” warning in the browser, and in Node.js it crashes the process by default. Always handle errors, at least at the top level.

4. Awaiting independent tasks one by one:

If the tasks don’t depend on each other, start them together with Promise.all, as shown above.

Conclusion:

Asynchronous code lets JavaScript start slow tasks and keep working while it waits. Callbacks were the first solution but quickly lead to deeply nested code. A Promise represents a future value that is pending, fulfilled or rejected, and can be chained with .then(), .catch() and .finally(). async/await builds on Promises and lets you write async code that reads top to bottom, with try...catch for errors. Use Promise.all, allSettled, race and any to run several tasks at once, and avoid the common traps: a missing await, await inside forEach, and unhandled errors.

In the next JavaScript lesson we will look at closures and scope, which explain how functions remember the variables around them.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume