Javascript 承诺保证 - Javascript 事件循环

Javascript Promise Guarantees - Javascript Event Loop

在 Mozilla Promise 文档中,有一个保证部分:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Guarantees

它包含以下语句:

Unlike "old-style", passed-in callbacks, a promise comes with some guarantees:

Callbacks will never be called before the completion of the current run of the JavaScript event loop.

这对我来说很有意义,也是我所期望的行为,但我正在寻找一些额外的文档来支持这个“保证”。

是否有某种规范明确记录/要求这样做?对于提供本机 Promise 实现的任何 javascript 运行时,这是否得到保证?是不是狂野的西部,你不能依赖它等等

Is there some sort of spec that explicitly documents / requires this?

promise 库使用的规范是 promise A+ 规范。这个特殊要求是 number 2.2.4. Pretty much any promise library you use will obey this, though if you need to check this, there are tests which can verify compliance with the spec

更重要的是,既然 promises 是语言的一部分,原生 promises 由 ECMAScript 规范管理。 Promises 首次在 2015 版中引入,在 section 25.4. The latest completed edition as of the time of this answer is the 2018 edition. The specific behavior you asked about is due to the section governing the .then method (found here), and the section on triggerPromiseReaction (found here). Each of those in turn references the enqueueJob operation (found here)

与任何内置 ECMAScript 功能一样,原生承诺的行为在 ECMAScript Spec.

中定义

第 9 版规范中的相关部分是 section 25.6.5.4.1, which defines the behavior of the .then method, and section 8.4.1,它描述了 EnqueueJob 操作(当 .then 在已解决的承诺上调用时使用)。

Is there some sort of spec that explicitly documents / requires this?

是的,Promises/A+ interoperability spec 需要这个。

但是不,该文档不是本机 Promise 实现的规范。

Is this guaranteed for any javascript runtime that provides a native Promise implementation?

是的。此功能是本机 Promise 对象的 ECMAScript 规范中详述的调度行为的隐式 属性。

Is it the wild west, and you can't depend on it?

你可以而且应该依赖它。由于 Promises/A+ 规范的流行,即使是大多数非本地承诺实现也能保证这一点。