下面的代码:
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回调?
1条答案
按热度按时间icnyk63a1#
重现此行为的最简单方法(节点14+、16+、18):
在同一个文件夹中添加一个新的
package.json
,只需执行以下操作:使用commonJS,输出是预期的输出。
不幸的是,目前还没有一个很好的解释,更多讨论here