The MDN documentation for the async function currently provides the following combined example of two ways to use await . I changed it a bit to highlight:
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);
It was a bit surprising for me. Why
const a = await resolveAfter2Seconds(20); const b = await resolveAfter2Seconds(30); return x + a + b;
sequentially allow two promises, and
return x + await p_a + await p_b;
seems to solve two promises at the same time? Is this behavior await specific, or a natural consequence of something else?
source share