Bitpath

Lesson 1 · Unit 08

Asynchronous code

Results that arrive later: promises, async and await

13 exercisesabout 3 min

What you practise

  • Why the result is not there yet, Promise<T>, async and await, Promise.all, errors in asynchronous code

Try a question from this lesson

Pick one

setTimeout runs a function later: here, after 10 milliseconds. In which order do the three messages print?

TypeScript
console.log("order coffee");
setTimeout(() => {
  console.log("coffee ready");
}, 10);
console.log("find a seat");

The ideas

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

Concept

Promises and await

Some work takes time: a timer, a file, a network call. The program does not freeze. It gets a promise: a placeholder for a result that arrives later.

A Promise<number> will hold a number; a Promise<void> only says "done". await pauses here until the promise is ready.

You will rarely build a promise by hand, as wait does. Mostly you await the ones you are given.

TypeScript
function wait(ms: number): Promise<void> {
  return new Promise((done) => {
    setTimeout(done, ms);
  });
}
console.log("start");
await wait(10);
console.log("10 ms later");

Concept

Several things at once

after(ms, v) is a helper here: a promise of v, ready after ms milliseconds.

A promise starts its work when it is created, not when it is awaited. Promise.all takes an array of promises and gives one promise of an array of results. The results keep the order of the array you passed, however long each took.

TypeScript
const a = after(20, "tea");
const b = after(10, "milk");
// both timers are running already

const both = await Promise.all([a, b]);
console.log(both.join(" + "));
// tea + milk

Concept

When a promise fails

A promise can fail as well as succeed. When you await a failed promise, the failure is thrown at that line, like any other error.

So try and catch work as you know them, as long as the await is inside the try. (wait(ms) is the timer helper again.)

TypeScript
async function load(id: number) {
  await wait(5);
  if (id < 0) throw new Error("bad id");
  return `user ${id}`;
}
try {
  console.log(await load(1));
  console.log(await load(-1));
} catch (err) {
  console.log("failed");
}
// user 1
// failed

9 more exercises in the app

  • 4× type the answer
  • 2× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 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