When is await resolved at the same time?

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); // prints 60 after 4 seconds. }); add2(10).then(v => { console.log(v); // prints 60 after 2 seconds. }); 

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?

+5
source share
1 answer
 async function add2(x) { const p_a = resolveAfter2Seconds(20); const p_b = resolveAfter2Seconds(30); return x + await p_a + await p_b; } 

In this expression, p_a and p_b are launched in parallel (i.e. as soon as you generate a promise), so when you wait for p_a and p_b, they will appear parallel, not consecutive.

To get other functionality (wait sequentially), you need to:

 return x + await resolveAfter2Seconds(20) + await resolveAfter2Seconds(30); 
+7
source

Source: https://habr.com/ru/post/1273035/


All Articles