The MDN documentation for async function currently gives the following combined example of two ways to use await
. I've reordered it just a bit for emphasis:
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function add1(x) {
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
}
async function add2(x) {
const p_a = resolveAfter2Seconds(20);
const p_b = resolveAfter2Seconds(30);
return x + await p_a + await p_b;
}
add1(10).then(v => {
console.log(v); // prints 60 after 4 seconds.
});
add2(10).then(v => {
console.log(v); // prints 60 after 2 seconds.
});
This was a bit surprising to me. Why does
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
resolve the two promises sequentially, while
return x + await p_a + await p_b;
seemingly resolves the two promises simultaneously? Is this behavior specified for await
specifically, or a natural consequence of something else?
A function with multiple await expressions in it will be suspended once at a time on each await expression until that Promise is settled, before unsuspending execution and moving onto the next await expression – not unlike the case we observe with generators and yield
. Source: ponyfoo.com/articles/understanding-javascript-async-await – Polypus