我正在阅读有关 nodejs promise 的文章 here .
然后我尝试运行以下示例代码(来自文章)
const p = Promise.resolve();
(async () => {
await p; console.log('after:await');
})();
p.then(() => console.log('tick:a'))
.then(() => console.log('tick:b'));
Node 版本之间的结果不一致。 Node v10 远离所有其他版本。
我用的是苹果机。
v8.17.0
after:await
tick:a
tick:b
v10.20.1
tick:a
tick:b
after:await
v12.17.0
after:await
tick:a
tick:b
v14.3.0
after:await
tick:a
tick:b
文章说 v10 引入了一个重大更改来纠正执行顺序,而 v8 的行为是一个错误。但是,当我使用 v12 和 v14 进行测试时,它们给出的结果与 v8 相同。
谁能告诉我为什么会这样?
最佳答案
这是由于 this change in the specs现在允许短路 await promiseInstance
不在内部将 promiseInstance
包装到新的 Promise 中,从而节省两个滴答(一个用于等待 promiseInstance
和一个唤醒 async 函数)。
Here is a detailed article来自规范补丁的作者,他们也恰好是 v8 开发者。在那里,他们解释了这种行为实际上已经存在于 nodejs v.8 中,但当时违反了规范,即一个错误,他们在 v.10 中修复了这个补丁,然后才使其成为官方的做法,并且它得到了直接在 v8 引擎中实现。
因此,如果您希望本应在此补丁之前发生的内联版本是
const p = Promise.resolve();
new Promise((res) => p.then(res)) // wait for p to resolve
.then((res) => Promise.resolve(res)) // wake up the function
.then((res) => console.log('after:await'));
p.then(() => console.log('tick:a'))
.then(() => console.log('tick:b'));
当补丁成功时
const p = Promise.resolve();
p.then(() => console.log('after:await'));
p.then(() => console.log('tick:a'))
.then(() => console.log('tick:b'));
关于node.js - JS Promise在nodejs版本之间的执行顺序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62032674/