What is the random factor in node v10 event loop?

对着背影说爱祢 提交于 2020-05-26 09:31:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!