Skip to main content
eLearner.app
Module 7 · Lesson 2 of 426/32 in the course~12 min
Module lessons (2/4)

async / await

async/await is a clearer syntax for working with Promises: the code reads like synchronous code, but behind the scenes it uses exactly the same Promises as the previous lesson.

async function

A function declared with async always returns a Promise.

JS
async function forty() {
  return 40;
}

forty(); // Promise { 40 }
forty().then((v) => console.log(v)); // 40

Even if you return a "normal" value, the function wraps it in a resolved Promise.

await

Inside an async function you can put await before a Promise: execution is paused until the Promise settles, then continues with the resolved value.

JS
async function sum() {
  const a = await Promise.resolve(10);
  const b = await Promise.resolve(20);
  return a + b; // 30
}

Equivalent in .then style (more verbose):

JS
function sum() {
  return Promise.resolve(10).then((a) => Promise.resolve(20).then((b) => a + b));
}

await propagates errors

If the Promise is rejected, await rethrows the error. You can catch it with a normal try/catch:

JS
async function read() {
  try {
    const x = await Promise.reject(new Error('no'));
    return x;
  } catch (err) {
    return 'error: ' + err.message;
  }
}

read(); // Promise { 'error: no' }

Arrow async

JS
const double = async (n) => n * 2;
double(5); // Promise { 10 }

Try it

Exercise#js.m7.l2.e1
Attempts: 0Loading…

Define an `async function addOne(p)` that receives a Promise of a number and returns (as a Promise) the number + 1. Use await.

Loading editor…
Show hint

const n = await p; return n + 1;

Solution available after 3 attempts

Review exercise

Exercise#js.m7.l2.e2
Attempts: 0Loading…

Define `sumTwo(pa, pb)` async: receives two Promises of numbers, returns their sum. Use two sequential awaits.

Loading editor…
Show hint

await each one, then return a + b.

Solution available after 3 attempts