Bitpath

Lesson 1 · Unit 08

Asynchronous code

Timers, promises, async and await

13 exercisesabout 3 min

What you practise

  • Callbacks and timers, why the result is not there yet, promises, async and await, Promise.all, errors in asynchronous code

Try a question from this lesson

Pick one

setTimeout(fn, 10) asks for the function to be called in about 10 milliseconds, and then returns at once. In what order do the letters print?

JavaScript
console.log("A");
setTimeout(() => console.log("B"), 10);
console.log("C");

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Later, not now

Some work takes time: a timer, reading a file, asking a server. JavaScript does not stop and wait for it.

Instead you hand over a function to be called when the work is done, a callback, and the program carries on with the next line. Code that finishes later is called asynchronous.

JavaScript
setTimeout(() => {
  console.log("2. the timer fired");
}, 10);

console.log("1. still running");

Concept

A promise

A promise is an object that stands for a result which is not there yet. Later it settles: fulfilled with a value, or rejected with an error.

Slow functions return a promise at once. .then(fn) says what to do with the value when it arrives.

This wait is our stand-in for anything slow.

JavaScript
function wait(ms, value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}
const p = wait(10, "tea");
p.then((v) => console.log("got " + v));
console.log("ordered");
// ordered
// got tea

Concept

async and await

await opens the box. It pauses the function until the promise settles, then gives you the value.

await is only allowed inside a function marked async. While that function is paused, the rest of the program keeps running.

Below, wait(ms, value) returns a promise for the value after that many milliseconds.

JavaScript
async function main() {
  console.log("asking");
  const v = await wait(10, "tea");
  console.log("got " + v);
}
main();
console.log("main is paused");
// asking
// main is paused
// got tea

9 more exercises in the app

  • 3× type the answer
  • 1× true or false
  • 3× multiple choice
  • 1× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy