
Having a discussion with someone and came across this oddity:
const wait = async () => new Promise(resolve => setTimeout(resolve, 1000));
async function case1() {
const {a, b} = {a: await wait(), b: await wait()};
return {a, b};
}
async function case2() {
return {a: await wait(), b: await wait()};
}
async function case3() {
const {a, b} = {a: wait(), b: wait()};
return {a: await a, b: await b};
}
async function case4() {
const {a, b} = {a: wait(), b: wait()};
const {c, d} = {c: await a, d: await b};
return {c, d};
}
function test() {
const start = new Date();
case1().then(() => console.log('case1:', +new Date() - start));
case2().then(() => console.log('case2:', +new Date() - start));
case3().then(() => console.log('case3:', +new Date() - start));
case4().then(() => console.log('case4:', +new Date() - start));
}
case1
and case2
both run in 2 seconds. case3
and case4
run in 1 second.
Is there some weird implicit Promise.all
or something??
Answer1:
You call the function wait()
without utilizing await
at case3
and case4
. That is the difference.
Answer2:
In case#3 the wait()
functions are called immediately, so there is only 1 second of timeout (for both of them), while in the other two (case#1 and case#2) the await
will "do it's job" and wait for the async call to return.
As you can see here, the console.log(Date())
is being called immediately for both calls.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
const wait = async () => new Promise(resolve => console.log(Date()) || setTimeout(resolve, 1000)); async function case3() { const {a, b} = {a: wait(), b: wait()}; return {a: await a, b: await b}; } function test() { const start = new Date(); case3().then(() => console.log('case3:', +new Date() - start)); } test();
And here it is being synchronized using the
await
:<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">
const wait = async () => new Promise(resolve => console.log(Date()) || setTimeout(resolve, 1000)); async function case1() { const {a, b} = {a: await wait(), b: await wait()}; return {a, b}; } function test() { const start = new Date(); case1().then(() => console.log('case1:', +new Date() - start)); } test();