JS Promise在nodejs版本之间的执行顺序不一致 [英] JS Promise's inconsistent execution order between nodejs versions

查看:259
本文介绍了JS Promise在nodejs版本之间的执行顺序不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关nodejs promise的文章此处.

I am reading the article about nodejs promise here.

然后,我尝试运行以下示例代码(来自本文)

Then I try running the following sample code (from the article)

const p = Promise.resolve();

(async () => {
  await p; console.log('after:await');
})();

p.then(() => console.log('tick:a'))
 .then(() => console.log('tick:b'));

节点版本之间的结果不一致.节点v10保留在所有其他版本之外.

The results are inconsistent between node versions. With node v10 staying out of all other versions.

我正在使用Mac.

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相同.

The article says that v10 introduces a breaking change to correct the execution order and the behavior of v8 is a bug. However, when I tested with v12 and v14, they give the same result as v8.

有人可以向我解释为什么会这样吗?

Could anyone explain to me why this happens?

推荐答案

这是由于这更改规格,现在允许短路await promiseInstance不在内部将promiseInstance包装到新的 Promise 中,从而节省了两个刻度(一个用于等待promiseInstance,另一个用于唤醒) async 函数).

This is due to this change in the specs which now allows shortcircuiting await promiseInstance to not wrap promiseInstance into a new Promise internally and hence saving two ticks (one for waiting for promiseInstance and one to wake up the async function).

此处是作者的详细文章规范补丁,也可能是v8开发者.在这里,他们解释了该行为在nodejs v.8中实际上已经存在,但是当时违反了规范,即他们在v.10中修复了一个错误,此补丁使之成为正式的行为方式,并且得到了直接在v8引擎中实现.

Here is a detailed article from the authors of the specs' patch, which also occur to be v8 devs. In there, they explain how that behavior was actually already in nodejs v.8 but was against the specs by then, i.e a bug, that they fixed in v.10, before this patch makes it the official way of doing, and it gets implemented in v8 engine directly.

因此,如果您希望在此修补程序发布之前应该已经出现的内联版本

So if you wish the inlined version that should have happened before this patch is

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'));

这篇关于JS Promise在nodejs版本之间的执行顺序不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆