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.
async function forty() {
return 40;
}
forty(); // Promise { 40 }
forty().then((v) => console.log(v)); // 40Even 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.
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):
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:
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
const double = async (n) => n * 2;
double(5); // Promise { 10 }Try it
Define an `async function addOne(p)` that receives a Promise of a number and returns (as a Promise) the number + 1. Use await.
Show hint
const n = await p; return n + 1;
Solution available after 3 attempts
Review exercise
Define `sumTwo(pa, pb)` async: receives two Promises of numbers, returns their sum. Use two sequential awaits.
Show hint
await each one, then return a + b.
Solution available after 3 attempts