Tutorials / Modern JavaScript: Async, Modules and the Browser / From callbacks to promises to async/await

From callbacks to promises to async/await

18 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

The same problem, three styles

Reading a user from a database, then their orders, then the products in those orders. Each step takes time, and each depends on the one before. JavaScript has solved this problem three times, each better than the last. You will meet all three in real code, so we will look at them in order.

Style 1: callbacks

The first approach is to pass a function to be called when the work is done.

function getUser(id, callback) {
  setTimeout(() => callback(null, { id, name: "Sara" }), 100);
}

getUser(1, (error, user) => {
  if (error) return console.log("Failed", error);
  console.log(user.name);
});

By convention the first argument of the callback is the error, or null. This works for one step. For several steps in a row, the callbacks nest inside each other:

getUser(1, (err, user) => {
  getOrders(user.id, (err, orders) => {
    getProducts(orders[0].id, (err, products) => {
      console.log(products);   // callback hell
    });
  });
});

The code drifts to the right, error handling is repeated at every level, and it is hard to read. This shape has a name, "callback hell", and it is why promises were invented.

Style 2: promises

A promise is an object that stands for a value that is not available yet. It is always in one of three states: pending, fulfilled (with a value) or rejected (with an error). Once it settles, it never changes.

You can create one with new Promise, and you call resolve or reject when the work finishes:

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

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

You consume a promise with .then for success, .catch for failure, and .finally for cleanup:

getUser(1)
  .then(user => {
    console.log(user.name);
    return getUser(2);          // returning a promise continues the chain
  })
  .then(user2 => console.log(user2.name))
  .catch(error => console.log("Failed:", error.message))
  .finally(() => console.log("done"));

The chain is flat. Each .then receives the value returned by the previous one, and if it returns a promise, the chain waits for it. One .catch at the end handles an error from any step above it.

Style 3: async and await

async/await is a way of writing promise code so that it looks synchronous. Mark a function async, and inside it you can await a promise. The function pauses until the promise settles, but the rest of the program keeps running.

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

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

async function main() {
  try {
    const user = await getUser(1);
    console.log("Got", user.name);

    await wait(200);

    const bad = await getUser(0);     // rejects, so jumps to catch
    console.log("never printed", bad);
  } catch (error) {
    console.log("Failed:", error.message);
  } finally {
    console.log("Finished");
  }
}

main();
console.log("main() has started, this prints first");

The output order is: the "has started" line first, then "Got Sara", then "Failed: Invalid id" and "Finished". The call to main() runs until its first await, then returns control to the caller. Everything after an await continues later, in the microtask queue we discussed in the event loop lesson.

Two facts to remember:

  1. An async function always returns a promise. If you return 5, the caller gets a promise that resolves to 5.
  2. await can only be used inside an async function, or at the top level of an ES module.

Errors work the way you would hope: a rejected promise becomes a thrown exception at the await, so ordinary try/catch handles it.

Running things in parallel

A common slip is to await independent jobs one after another:

const a = await fetchA();   // waits 1 second
const b = await fetchB();   // then waits another second

If fetchB does not need the result of fetchA, start them both and wait together with Promise.all:

const [a, b] = await Promise.all([fetchA(), fetchB()]);

This takes as long as the slowest one, not the sum. Promise.all fails as soon as any promise fails. If you want every result whether it succeeded or not, use Promise.allSettled. Promise.race gives you the first one to settle, which is a way to build a timeout. Promise.any gives the first one to succeed.

const results = await Promise.allSettled([getUser(1), getUser(0)]);
console.log(results.map(r => r.status)); // ["fulfilled", "rejected"]

Await in loops

await inside a for...of loop runs the steps one by one, which is correct when order matters. forEach does not wait for async callbacks, so this does not work as you would expect:

ids.forEach(async id => {
  await getUser(id);          // forEach does not wait for these
});
console.log("this runs before they finish");

Use for...of for sequence, or await Promise.all(ids.map(getUser)) for parallel.

Which style should you use

I write async/await for nearly everything. It reads in order, and try/catch works as usual. I use .then for short one-liners and Promise.all and friends for combining. Callbacks stay for event handlers and older APIs. If you must use a callback-based API, wrap it in a promise once, as we did with wait, and use await after that.

Common mistakes

  • **Forgetting to await.** You get a pending promise, not the value. console.log(getUser(1)) prints Promise { <pending> }.
  • **Forgetting the async keyword.** await inside a normal function is a syntax error.
  • Awaiting jobs in sequence that could run in parallel. Use Promise.all.
  • Not handling rejections. An unhandled rejected promise is an error in Node and a console warning in the browser.
  • **Using async with forEach.** It does not wait.
  • **Writing new Promise around something that already returns a promise.** Return it directly.

Try it yourself

  1. Convert the nested callback example to promises, then to async/await.
  2. Use wait to build a function countdown(n) that logs n, n-1, ... 1 with one second between lines.
  3. Start three wait(300) calls. Measure the time with Promise.all and with sequential await. Compare.
  4. Write withTimeout(promise, ms) using Promise.race that rejects if the promise takes too long.
javascript
function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

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

async function main() {
  try {
    const user = await getUser(1);
    console.log("Got", user.name);

    await wait(200);

    const bad = await getUser(0);     // rejects, so jumps to catch
    console.log("never printed", bad);
  } catch (error) {
    console.log("Failed:", error.message);
  } finally {
    console.log("Finished");
  }
}

main();
console.log("main() has started, this prints first");

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account