Lesson 10 of 1912:00 video

Asynchronous JavaScript

Why a timer set to zero milliseconds still runs last: the call stack, the task queue and the event loop. Then callbacks, promises, and async and await, each run through the event loop step by step: callback hell, the microtask queue, promise chains, try and catch with await, and Promise.all.

In this lesson

  1. 0:00 Intro
  2. 0:58 One thing at a time
  3. 1:57 The event loop
  4. 3:37 Callbacks
  5. 5:08 Promises
  6. 7:42 async and await
  7. 9:37 Promise.all
  8. 10:16 Back to the three lines
  9. 11:19 Next time

Three lines of code. The first prints 1 and the third prints 3. The line between them sets a timer that prints 2, and the timer is set to zero milliseconds:

console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
// 1
// 3
// 2

A timer with nothing to wait for, and it still comes last. It does in a plain <script>, in a module, in the browser console and in Node. By the end of this lesson you’ll know what it was waiting for, the event loop, and three ways to write code that has to wait: callbacks, promises, and async and await, with the loop running underneath each one.

One thing at a time

Until now, every program in this series ran in order: one line, then the next, each finishing before the next began. That’s because JavaScript has a single call stack, the pile of calls waiting on each other, and whatever is on it runs to the end before anything else starts.

But some things take time: a timer, a file coming over the network, a user who hasn’t clicked yet. If JavaScript stopped and waited for each one, nothing else could run. In a browser, the whole page would freeze. So JavaScript doesn’t wait. It hands the waiting to the browser, carries on with the next line, and picks up the result later. Code that works this way is called asynchronous.

The event loop

Run the three lines again, slowly.

Line one: console.log goes on the stack, prints 1, and comes off.

Line two calls setTimeout with a function and a delay. setTimeout isn’t part of the JavaScript language. It belongs to the browser, and the HTML standard defines it. So all line two does is hand the function over, and it’s done. The browser runs the timer. Zero milliseconds later the time is up, but the browser can’t just run the function, because JavaScript is busy: the script is still on the stack. So the function joins a line, the task queue.

Line three prints 3. Now the script is finished and the stack is empty. That’s the moment the event loop is watching for. It has one rule: wait for the stack to empty, then take the next function in line and run it. That prints 2.

So zero milliseconds never meant “now”. It meant: as soon as everything already running has finished. A delay is a minimum, too. If the stack stays busy for three seconds, a one-second timer runs three seconds in.

Node has no browser, so Node itself runs the timers and the loop. The three lines print the same there.

Why try can’t catch a callback

That picture explains a limit of try. Here’s Heron, a rocket with 40% fuel, and a launch function that throws an error under 50:

const heron = { name: "Heron", fuel: 40 };

function launch(ship) {
  if (ship.fuel < 50) {
    throw new RangeError(`${ship.name} needs 50% fuel, has ${ship.fuel}%`);
  }
  console.log(`${ship.name} lifts off`);
}

try {
  setTimeout(() => launch(heron), 1000);
} catch (error) {
  console.log(`Grounded: ${error.message}`);
}
// one second later:
// Uncaught RangeError: Heron needs 50% fuel, has 40%
//     at launch (mission.js:5:11)
//     at mission.js:11:20

The try block hands the callback to the browser, and ends. The script ends too. One second later, the callback lands on an empty stack, and launch throws. The error goes looking for a catch block, and there’s nothing under it. The try block finished a second ago. try only covers code that runs while it’s open.

Callbacks

So how do you run something after a step that takes time? Say refueling takes two seconds, with a timer standing in for the real work. Call refuel, then launch on the next line:

function refuel(ship) {
  setTimeout(() => {
    ship.fuel = 100;
  }, 2000);
}

refuel(heron);
launch(heron);
// RangeError: Heron needs 50% fuel, has 40%

JavaScript doesn’t wait: the launch runs with the tank still at 40. In a browser the tank does reach 100, two seconds after the launch failed.

The oldest fix is the one setTimeout itself uses: a callback. Give refuel a second parameter, the function it should call once the tank is full, and put the launch in that function:

function refuel(ship, onDone) {
  setTimeout(() => {
    ship.fuel = 100;
    onDone();
  }, 2000);
}

refuel(heron, () => {
  launch(heron);
});
// two seconds later: Heron lifts off

Here’s that run in the event loop. refuel hands its timer to the browser, along with the function that fills the tank, and returns. The script ends, and the stack is empty. Two seconds later the time is up, and that function joins the task queue. The loop puts it on the stack: it fills the tank, then calls onDone, and the launch runs inside it. So a callback is a function you hand over now, for the loop to run later.

A real launch has more steps: refuel, then check the weather, then count down, then launch. Here are the two new steps written the same way, with timers standing in again. The weather check hands its callback an error when there’s a storm, and the forecast when there isn’t:

let storm = false;

function checkWeather(onDone) {
  setTimeout(() => {
    if (storm) {
      onDone(new Error("Storm over the pad"));
    } else {
      onDone(null, "clear");
    }
  }, 1000);
}

function countdown(seconds, onDone) {
  setTimeout(() => onDone(null), seconds * 1000);
}

Each step has to sit inside the callback of the step before it, so every step is one more trip through the queue, and pushes the code further to the right:

refuel(heron, () => {
  checkWeather((error, weather) => {
    countdown(3, () => {
      launch(heron);
    });
  });
});
// six seconds later: Heron lifts off

And any step can fail. try can’t help, as we just saw, so every callback has to check for an error itself:

refuel(heron, (error) => {
  if (error) {
    console.log(`Grounded: ${error.message}`);
    return;
  }
  checkWeather((error, weather) => {
    if (error) {
      console.log(`Grounded: ${error.message}`);
      return;
    }
    countdown(3, (error) => {
      if (error) {
        console.log(`Grounded: ${error.message}`);
        return;
      }
      launch(heron);
    });
  });
});

Three copies of the same check, and the deepest lines sit four levels in. This shape has a name: callback hell.

Promises

In 2015, JavaScript got a better tool, the promise: an object that stands for a result that isn’t ready yet. Rewrite refuel so it takes only the ship, and returns a promise right away:

function refuel(ship) {
  return new Promise((resolve) => {
    setTimeout(() => {
      ship.fuel = 100;
      resolve(ship);
    }, 2000);
  });
}

const promise = refuel(heron);
console.log(promise); // Promise { <pending> }

At first, that promise is pending. Two seconds later it’s fulfilled, and it holds a value: here, the refueled ship. If the work had failed, it would be rejected, and hold an error instead. Either way, a promise settles once and never changes again.

To use the result, call the promise’s then method and hand it a function. After the promise is fulfilled, then passes its value to your function:

refuel(heron).then(launch);
// two seconds later: Heron lifts off

That line reads: refuel Heron, then launch. launch goes in without parentheses, because you’re handing the function over, not calling it.

The microtask queue

Here’s that line in the event loop. refuel starts its timer and hands back a pending promise, and then gives that promise launch, to call once it’s fulfilled. The script ends. Two seconds later, the timer’s function joins the task queue. The loop runs it: it fills the tank and calls resolve, and the promise is fulfilled.

Even so, launch doesn’t run on the spot. Once a promise settles, the functions waiting on it go in a line of their own: the microtask queue. Whenever the stack empties, the loop runs everything in that line before it takes another task. The timer’s function finishes, the stack is empty, and launch is first in line.

Most promises are handed to you: fetch, which loads data over the network, returns one. When you do make one, it comes from new Promise, with a function that’s handed two functions of its own. When the work is done, call the first, resolve, with the value. If it fails, call the second, reject, with an error. Here are the other two steps as promises:

let storm = false;

function checkWeather() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (storm) {
        reject(new Error("Storm over the pad"));
      } else {
        resolve("clear");
      }
    }, 1000);
  });
}

function countdown(seconds) {
  return new Promise((resolve) => {
    setTimeout(resolve, seconds * 1000);
  });
}

Chains

then gives something back too: a new promise, for whatever your function returns. So you can call then on that one as well, and build a chain. And if your function returns a promise of its own, the chain waits for it before moving on. Here’s the whole launch:

refuel(heron)
  .then(() => checkWeather())
  .then(() => countdown(3))
  .then(() => launch(heron))
  .catch((error) => console.log(`Grounded: ${error.message}`));
// six seconds later: Heron lifts off

Four steps in a column, and nothing is nested. Errors get simpler too. When any step’s promise is rejected, the steps after it are skipped, and the error travels down the chain to the first catch. Set storm to true and run it again: the weather check rejects, the countdown and the launch never run, and one catch, the last line of the chain, prints why Heron is grounded:

Grounded: Storm over the pad

An error thrown inside a then function rejects the chain the same way, so a RangeError from launch would land in the same catch. And .finally(() => ...) at the end runs either way.

async and await

A chain is flat, but every step is still wrapped in a function. So in 2017, JavaScript added two keywords. Write async in front of a function, and inside it you can use await. Put await in front of a promise, and the function pauses on that line until the promise settles, then carries on. Here’s the same launch as an async function:

async function mission(ship) {
  await refuel(ship);
  const weather = await checkWeather();
  console.log(`Weather: ${weather}`);
  await countdown(3);
  launch(ship);
}

mission(heron);
console.log("Mission started");
// Mission started
// three seconds later: Weather: clear
// six seconds later:   Heron lifts off

It reads like the code from every earlier lesson, top to bottom. And when a promise holds a value, await hands it over, ready to keep in a variable, like weather here.

Only this function pauses, though. Here’s the run in the event loop: mission runs to its first await, and the refuel’s promise is pending, so the function steps off the stack. It isn’t finished, only paused, and it keeps its place. The stack is free, so the next line runs: that’s why Mission started prints first. Two seconds later, the timer’s task fulfills the promise, so the rest of the function joins the microtask queue, and the loop puts it back on the stack, right after the await. Underneath, nothing is new. These are the same promises, and an async function always returns one itself: mission(heron) hands back a pending promise, which is fulfilled when the function ends.

await works inside an async function, and at the top level of a module. Anywhere else it’s a SyntaxError.

Errors with await

When a promise you’re awaiting is rejected, await throws its error, right on that line. So try and catch work again:

async function mission(ship) {
  try {
    await refuel(ship);
    const weather = await checkWeather();
    console.log(`Weather: ${weather}`);
    await countdown(3);
    launch(ship);
  } catch (error) {
    console.log(`Grounded: ${error.message}`);
  }
}

storm = true;
mission(heron);
console.log("Mission started");
// Mission started
// three seconds later: Grounded: Storm over the pad

Why does try work here, when it couldn’t cover a timer’s callback? Because this function never left its try block. It paused inside it, and when the promise settles, it wakes up in the same place, still inside.

Without the try block, nothing handles the rejection, and the browser console says Uncaught (in promise) Error: Storm over the pad.

Promise.all

await has one trap. Three rockets need fuel, two seconds each. Await them in a loop, and they go one at a time:

const kestrel = { name: "Kestrel", fuel: 80 };
const osprey = { name: "Osprey", fuel: 95 };

async function refuelAll(ships) {
  for (const ship of ships) {
    await refuel(ship);
  }
}

refuelAll([kestrel, heron, osprey]); // six seconds

But one refuel doesn’t depend on another. So start all three first. Each call returns its promise right away, and now three timers are running at once. Then hand the promises to Promise.all. It gives back a single promise, fulfilled once all three are, with their values in an array:

async function refuelAll(ships) {
  const promises = ships.map((ship) => refuel(ship));
  await Promise.all(promises);
}

refuelAll([kestrel, heron, osprey]); // two seconds

The values come back in the promises’ order, not the order they finished. If one promise is rejected, Promise.all rejects at once, with that error.

When each step needs the one before it, await them in order. When they don’t, start them together.

Back to the three lines

Which brings us back to the three lines we started with. Add a fourth at the bottom. Promise.resolve() makes a promise that’s already fulfilled, and its then prints 4:

console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
Promise.resolve().then(() => console.log(4));
// 1
// 3
// 4
// 2

The timer was set first, with no delay. The promise came last. And the timer still loses.

Watch the queues. Line two hands its timer to the browser, and zero milliseconds later, its function joins the task queue. Line four’s promise is already fulfilled, so its function joins the microtask queue at once: a function handed to then never runs on the spot, even if its promise settled long ago. The script ends, the stack is empty, and the loop empties the microtask queue first, which prints 4. Only then does it take a task, which prints 2.

So the full order is:

  1. Whatever is running now.
  2. Every promise callback: then, catch, finally, and the code after await.
  3. Only then, the next timer, click or network reply.

Summary

  • JavaScript runs one thing at a time and doesn’t wait. Anything slow is handed off, and its result comes back later as a function waiting in a queue.
  • The event loop runs the next queued function only once the call stack is empty, which is why setTimeout(..., 0) runs after the rest of the script.
  • A callback is a function to call when the work is done. Steps that depend on each other nest, and every callback checks for its own errors.
  • A promise stands for a result that isn’t ready yet: pending, then fulfilled or rejected, once. then returns a new promise, so steps chain in a column, and one catch handles them all.
  • async and await let you write the waiting from top to bottom, and catch its errors with try and catch. await pauses only its own function.
  • Start steps that don’t depend on each other together, and wait for them with Promise.all.
  • When the stack empties, every microtask (promise callbacks) runs before the next task (timers).
Video transcript

Intro

Three lines of code. The first prints one. The third prints three. The line between them sets a timer that prints two, and the timer is set to zero milliseconds. No delay at all. Run it. One. Three. Two. A timer with nothing to wait for, and it still came last. So what was it waiting for? Today, we find out.

By the end of this video, you'll understand three things. One: the event loop, which decides what runs next, and why that timer ran last. Two: callbacks and promises: which queue each one waits in, and why a chain of promises beats callbacks nested inside callbacks. Three: how async and await let you write code that waits as plain lines, top to bottom, and catch its errors with try and catch.

One thing at a time

Until now, every program in this series ran in order: one line, then the next, each finishing before the next began. That's because JavaScript has a single call stack, the pile of calls waiting on each other that we met in the functions episode, and whatever is on it runs to the end before anything else starts. But some things take time: a timer, a file coming over the network, a user who hasn't clicked yet. If JavaScript stopped and waited for each one, nothing else could run. In a browser, the whole page would freeze. So JavaScript doesn't wait. It hands the waiting to the browser, carries on with the next line, and picks up the result later. Code that works this way is called asynchronous. First, the event loop: how the result gets back in. Then three ways to write code for it: callbacks, promises, and async and await, each with the loop running underneath.

The event loop

Run the three lines again, slowly. Line one: console dot log goes on the stack, prints one, and comes off. Line two calls setTimeout with a function and a delay. But setTimeout isn't part of the JavaScript language. It belongs to the browser. So all line two does is hand the function over, and it's done. The browser runs the timer. Zero milliseconds later the time is up, but the browser can't just run the function, because JavaScript is busy: our script is still on the stack. So the function joins a line, the task queue. Line three prints three. Now the script is finished and the stack is empty. That's the moment the event loop is watching for. The event loop has one rule: wait for the stack to empty, then take the next function in line and run it. Two. So zero milliseconds never meant now. It meant: as soon as everything already running has finished.

That picture settles a note we left last time: try only covers code that runs while it's open. Here's a try block around a setTimeout. Its callback launches Heron, a rocket with forty percent fuel, and our launch function throws an error under fifty. Watch the stack. The try block hands the callback to the browser, and ends. The script ends too. One second later, the callback lands on an empty stack, and launch throws. The error goes looking for a catch block, and there's nothing under it. The try block finished a second ago. Uncaught.

Callbacks

So how do you run something after a step that takes time? Say refueling takes two seconds, with a timer standing in for the real work. Call refuel, then launch on the next line, and JavaScript doesn't wait: the launch runs with the tank still at forty. RangeError. The oldest fix is the one setTimeout itself uses: a callback. Give refuel a second parameter: the function it should call once the tank is full. Put the launch in that function, and two seconds later, Heron lifts off.

Here's that run in the event loop. refuel hands its timer to the browser, along with the function that fills the tank, and returns. The script ends, and the stack is empty. Two seconds later the time is up, and that function joins the task queue. The loop puts it on the stack. It fills the tank, then calls onDone, and the launch runs inside it. Heron lifts off. So a callback is a function you hand over now, for the loop to run later.

But a real launch has more steps: refuel, then check the weather, then count down, then launch. Each step has to sit inside the callback of the step before it, so every step is one more trip through the queue, and pushes the code further to the right. And any step can fail. try can't help, as we just saw, so every callback has to check for an error itself. This shape has a name: callback hell.

Promises

In 2015, JavaScript got a better tool, the promise: an object that stands for a result that isn't ready yet. Rewrite refuel so it takes only the ship, and returns a promise right away. At first, that promise is pending. Two seconds later it's fulfilled, and it holds a value: here, the refueled ship. If the work had failed, it would be rejected, and hold an error instead. Either way, a promise settles once and never changes again. To use the result, call the promise's then method and hand it a function. After the promise is fulfilled, then passes its value to your function. So this line reads: refuel Heron, then launch. And where does the promise come from? Inside refuel: new Promise, with a function that's handed two functions of its own. When the work is done, call the first, resolve, with the value. If it fails, call the second, reject, with an error.

Now the same launch in the event loop, with a promise. refuel starts its timer and hands back a pending promise. then gives that promise launch, to call once it's fulfilled. The script ends. Two seconds later, the timer's function joins the task queue. The loop runs it: it fills the tank and calls resolve, and the promise is fulfilled. Even so, launch doesn't run on the spot. Once a promise settles, the functions waiting on it go in a line of their own: the microtask queue. Whenever the stack empties, the loop runs everything in that line before it takes another task. The timer's function finishes, the stack is empty, and launch is first in line. Heron lifts off.

then gives something back too: a new promise, for whatever your function returns. So you can call then on that one as well, and build a chain. And if your function returns a promise of its own, the chain waits for it before moving on. Here's the whole launch: refuel, then check the weather, then count down, then launch. Four steps in a column, and nothing is nested. Errors get simpler too. When any step's promise is rejected, the steps after it are skipped, and the error travels down the chain to the first catch. Say there's a storm. The weather check rejects, the countdown and the launch never run, and one catch, the last line of the chain, prints why Heron is grounded.

async and await

A chain is flat, but every step is still wrapped in a function. So in 2017, JavaScript added two keywords. Write async in front of a function, and inside it you can use await. Put await in front of a promise, and the function pauses on that line until the promise settles, then carries on. Here's the same launch as an async function: await the refuel, await the weather, await the countdown, then launch. It reads like the code from every earlier episode, top to bottom. And when a promise holds a value, await hands it over, ready to keep in a variable. Underneath, nothing is new: these are the same promises, and an async function always returns one itself.

So what does the event loop do while a function awaits? The mission starts like any call, and runs to its first await. The refuel's promise is pending, so the function steps off the stack. It isn't finished, only paused, and it keeps its place. Only this function pauses, though: the stack is free, so the next line runs, and the console prints Mission started. Two seconds later, the timer's task fulfills the promise, so the rest of the function joins the microtask queue. The loop puts it back on the stack, right after the await, and it runs on to the next one.

Errors change too. When a promise you're awaiting is rejected, await throws its error, right on that line. So try and catch work again. Wrap the awaits in one try block, send in the storm, and the catch block prints why Heron is grounded. Why does try work here, when it couldn't cover a timer's callback? Because this function never left its try block. It paused inside it, and when the promise settles, it wakes up in the same place, still inside.

Promise.all

await has one trap. Three rockets need fuel, two seconds each. Await them in a loop, and they go one at a time: six seconds. But one refuel doesn't depend on another. So start all three first. Each call returns its promise right away, and now three timers are running at once. Then hand the promises to Promise dot all. It gives back a single promise, fulfilled once all three are, with their values in an array. Await that: two seconds. When each step needs the one before it, await them in order. When they don't, start them together.

Back to the three lines

Which brings us back to the three lines we started with. Add a fourth at the bottom. Promise dot resolve makes a promise that's already fulfilled, and its then prints four. The timer was set first, with no delay. The promise came last. Run it. One, three, four, two. The timer still loses. Watch the queues. Line two hands its timer to the browser, and zero milliseconds later, its function joins the task queue. Line four's promise is already fulfilled, so its function joins the microtask queue at once. The script ends, the stack is empty, and the loop empties the microtask queue first: four. Only then does it take a task: two. So the full order is: whatever is running now, then every microtask, and only then the next task, like a timer.

Next time

That's asynchronous JavaScript in one line: JavaScript runs one thing at a time and doesn't wait, so anything slow comes back later, through the event loop's queues; a promise stands for that later result; and async and await let you write the waiting from top to bottom. Next time, we split a program across files: how a module shares what it chooses with import and export, and keeps everything else to itself.

Learn more