运行下面的代码将得到:c,a,d,b
// case 1
const test = async () => {
new Promise((resolve) => {
resolve('a');
}).then(r => console.log(r));
process.nextTick(() => {
console.log('c');
});
console.log(await 'd');
return 'b';
};
(async () => {
const r = await test();
console.log(r);
})();
但是,如果我将 process.nextTick 放在 await 'd'
下方
// case 2
const test = async () => {
new Promise((resolve) => {
resolve('a');
}).then(r => console.log(r));
console.log(await 'd');
process.nextTick(() => {
console.log('c');
});
new Promise((resolve) => {
resolve('e');
}).then(r => console.log(r));
return 'b';
};
(async () => {
const r = await test();
console.log(r);
})();
我得到:a,d,e,b,c
为什么process.nextTick的执行顺序会这样变化?
根据我有限的知识,nextTick
在 Promise.resolve()
之前运行,如 case1
所示,所以我希望得到 a,d,c,e,b
而不是 case2
a,d,e,b,c
最佳答案
免责声明
Node.js 绝对不保证 process.nextTick
和 promise 回调的顺序。
我们可能在补丁版本中打破它,因为我们不认为它是公共(public) API 的一部分。
您不可以依赖 promises 和 nextTick
的内部顺序来做事。
这个特殊情况
这种特殊情况有时是我们处理 promise /回调的方式中的一个“错误”。它最近已修复(在 semver 补丁中)——通过获取夜间版本的 Node,您将看到预期的执行顺序。
关于node.js - NodeJS eventloop 执行顺序(process.nextTick and promise),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50199376/