CHAPTER 12 · 3 lessons · 39 exercises

Wait for slow work

Represent "a result that arrives later" with a Promise, write it straight-line with async / await, and prepare for it to fail.

0 / 39 solved

Work that fetches data over the network, or that needs to pause before continuing — this kind of work that does not finish right away cannot be handled by the writing style from earlier chapters, because it breaks the assumption that everything runs top to bottom in order. This chapter builds three ways of thinking about that "slow work".

First, Promise. An object that represents "a promise that a result will arrive later", holding one of three states: succeeded, failed, or not yet known. You receive the result with .then() and the failure with .catch(). Getting comfortable with this idea first makes the next two much easier to follow.

Next, async / await. Chaining .then() after .then() nests deeper and gets harder to read as the work piles up. Inside a function marked async, using await lets you write asynchronous work with the same straight-line look as synchronous work. Underneath it is still a Promise — only how it reads changes.

Finally, handling errors in asynchronous work. Talking over a network assumes failure is possible: the server might be down, the connection might drop, the response might not be what you expected. A failure inside awaited work is caught by the very same try / catch you already know. Discovering that the same tool you use for synchronous failures also covers asynchronous ones is how this chapter wraps up.

Finish this chapter and you will have the full shape of real frontend work in hand: talk to a server, receive the answer, and put it on the screen.

Lessons in this chapter

The basics of Promise

  1. 94Boxes of promises (Promise)Create a Promise, resolve the outcome, and receive it with .then().Go to the exercises

Write it with async / await

  1. 95Waiting in sequence (async / await)Use await inside async functions to write asynchronous code straight from top to bottom.Go to the exercises

Prepare for asynchronous errors

  1. 96Guarding against async errorsCatch await failures using try / catch so network issues do not crash the application.Go to the exercises

This is the last chapter of the course.