NodeJS process.nextTick before Promise.resolve().then?

9nvpjoqh  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(117)

下面的代码:

process.nextTick( () => console.log("nextTick 1") );
process.nextTick( () => { 
    console.log("nextTick 2"); 
    Promise.resolve("Resolved promise inside nextTick").then(console.log); 
})

Promise.resolve("Resolved promise 1").then(console.log);
Promise.reject("Rejected promise 2").catch(console.log);

setImmediate( () => {
    console.log("setImmediate");
    Promise.resolve("Resolved promise inside setImmediate").then(console.log);
    Promise.reject("Rejected promise inside setImmediate").catch(console.log);
    process.nextTick( () => console.log("nextTick 3") );
})

在节点v14.17.0中输出

Resolved promise 1
Rejected promise 2
nextTick 1
nextTick 2
Resolved promise inside nextTick    
setImmediate
nextTick 3
Resolved promise inside setImmediate
Rejected promise inside setImmediate

为什么前两个Promise.then/catch回调在process.nextTick回调之前调用?不应该像setImmediate部分那样,process.nextTick回调先于Promise回调?

icnyk63a

icnyk63a1#

重现此行为的最简单方法(节点14+、16+、18):
在同一个文件夹中添加一个新的package.json,只需执行以下操作:

{
  "type": "commonjs" //I assume you have here "module"
}

使用commonJS,输出是预期的输出。
不幸的是,目前还没有一个很好的解释,更多讨论here

相关问题