Wait for slow work

INPUT · Slides

Waiting in sequence (async / await)

01 / 05

then-chains get hard to read

While Promises are capable, deeply nested .then calls or long chains become difficult to follow.

We want to write waiting code straightforwardly from top to bottom, just like synchronous code. That is why async and await were added.

02 / 05

Asynchronous functions: async

Adding async before a function turns it into an asynchronous function.

Only inside async functions can you use await. Also, the return value of an async function is automatically wrapped in a Promise.

const hello = async () => {  return "Hello";};hello().then((msg) => console.log(msg));

Result

Hello

03 / 05

Pausing until done: await

Placing await before a Promise pauses on that line until the Promise completes, and unpacks the resolved value directly!

No .then callbacks needed: values land right in standard variables.

const run = async () => {  const p = Promise.resolve("Package");  const item = await p;  console.log(item);};run();

Result

Package

04 / 05

Progressing sequentially

Stacking await statements executes them in clean sequential order: the first finishes, then the second, then the third.

You write code that matches human linear thought without convoluted nesting.

const run = async () => {  const a = await Promise.resolve(10);  const b = await Promise.resolve(20);  console.log(a + b);};run();

Result

30

05 / 05

Check the key points

Let us review the ideas:

  • Mark functions with async
  • Place await before Promises to wait for outcomes
  • Values unpack directly into variables
  • Read and write linearly from top to bottom

Let us practice using await!