| 1 |
function resolveAfter2Seconds(x) { |
| 2 |
return new Promise((resolve) => { |
| 3 |
setTimeout(() => { |
| 4 |
resolve(x); |
| 5 |
}, 2000); |
| 6 |
}); |
| 7 |
} |
| 8 |
|
| 9 |
// async function expression assigned to a variable |
| 10 |
const add = async function (x) { |
| 11 |
const a = await resolveAfter2Seconds(20); |
| 12 |
const b = await resolveAfter2Seconds(30); |
| 13 |
return x + a + b; |
| 14 |
}; |
| 15 |
|
| 16 |
add(10).then((v) => { |
| 17 |
console.log(v); // prints 60 after 4 seconds. |
| 18 |
}); |
| 19 |
|
| 20 |
// async function expression used as an IIFE |
| 21 |
(async function (x) { |
| 22 |
const p1 = resolveAfter2Seconds(20); |
| 23 |
const p2 = resolveAfter2Seconds(30); |
| 24 |
return x + (await p1) + (await p2); |
| 25 |
})(10).then((v) => { |
| 26 |
console.log(v); // prints 60 after 2 seconds. |
| 27 |
}); |
| 28 |
|
| 29 |
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function |
| 30 |
|