Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). Would appreciate insights from experts.
A recent Google dev blog suggests that delaying your await
call on two async/await functions can cut wait time in half.
Original post: https://web.dev/async-functions/#careful-avoid-going-too-sequential
However, this logic does not seem to apply on node.js (both v16 and v18/lts).
If we wrap their example in an async IIFE, we can test it using the following code:
(async () => {
function wait(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
const t = 500
const msg = 'done'
const wait1 = wait(t, msg); // Start a 500ms timer asynchronously…
const wait2 = wait(t, msg); // …which means this timer runs in parallel.
await wait1; // Wait 500ms for the first timer…
await wait2; // …by which time the second timer has already finished.
console.log(wait1, wait2)
})()
Observe the values of wait1 and wait2 in the concluding console.log
statement.
console.log(wait1,wait2)
// Promise { 'done' } Promise { 'done' }
Why do wait1
and wait2
still remain unresolved promises even after awaiting them?
This additional observation raises further doubts about the logic flow here. When we await those variables again in console.log, the promises are finally resolved...
console.log(await wait1, await wait2)
// done done
So, by awaiting these variables again, we eventually get resolved promise values?
Is this discrepancy between Node and Chrome's V8 implementation intentional, or is it related to how we handle resolved promise values versus just awaiting a function with a void
response?