问题
My question is about nodejs event loop
Consider this code
(async () => {
let val = 1
const promise = new Promise(async resolve => {
resolve()
await new Promise(async r => {
setTimeout(r)
})
await promise
val = 2
})
await promise
await new Promise(resolve => setTimeout(resolve))
console.log(val)
})()
With node 10.20.1 (latest version of node 10)
for ((i = 0; i < 30; i++)); do /opt/node-v10.20.1-linux-x64/bin/node race-timeout.js; done
With node 12.0.0 (first version of node 12)
for ((i = 0; i < 30; i++)); do /opt/node-v12.0.0-linux-x64/bin/node race-timeout.js; done
The result of node 10
1 2 2 1 1 2 2 1 2 1 1 1 1 1 2 1 1 2 1 2 1 1 2 2 1 2 1 1 2 1
The result of node 12
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
So far, I have known that node is a single-thread language. Everything is well-determined and executed in an exact order except when there is intervention of the poll phase.
The above code does not include any undetermined factors (like IO, network, ...). I expected that the result should be the same. However, with node v10, it is not.
What is the random factor in node v10?
来源:https://stackoverflow.com/questions/61627447/what-is-the-random-factor-in-node-v10-event-loop