Promise/A+ 规范第 2.2.4 条背后的意图是什么? [英] What is the intention behind clause 2.2.4 of Promise/A+ spec?

查看:12
本文介绍了Promise/A+ 规范第 2.2.4 条背后的意图是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

promise/a+ 规范的第 2.2.4 条说:

Clause 2.2.4 of the promise/a+ spec says:

onFulfilled 或 onRejected 在执行前不能被调用上下文堆栈仅包含平台代码.

onFulfilled or onRejected must not be called until the execution context stack contains only platform code.

然后在注释中指出:

这里的平台代码"是指引擎、环境和promise实现代码.在实践中,这一要求确保onFulfilled 和 onRejected 异步执行,在事件之后调用 then 的循环,并使用新的堆栈.

Here "platform code" means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack.

这样做的用意是为了保证当一个链中有大量的onFulfilled函数时,它们的执行不会导致线程阻塞?

Is the intention of this to ensure that when there is a large amount of onFulfilled functions in a chain, the execution of them does not cause the thread to block?

或者在我没有阅读的两行之间有什么其他的东西吗?

Or is there anything else that is between the lines that I am not reading?

推荐答案

原因是当回调总是异步而不是可能异步时,它提供了更一致的和可靠的api使用.考虑以下代码

The reasoning is that when the callbacks are always asynchronous instead of possibly asynchronous, it gives more consistent and reliable api to use. Consider the following code

var pizza;
browseStackOverflow().then(function(){
    eatPizza(pizza);
});
pizza = yesterdaysLeftovers;

现在该代码段明确假设 onFulfilled 不会立即被调用,如果不是这样,我们很快就会有未使用的比萨饼,我们会饿着肚子.虽然在这种情况下,错误很容易修复,但执行顺序更容易遵循,因此当您可以做出这样的一些假设时,api 更易于使用.

Now that snippet clearly assumes the onFulfilled will not be called right away and if that wasn't the case we would soon have unused pizza lying around and we'd be left hungry. Although in this case the bug would be easy enough to fix, the order of execution is easier to follow and thus the api is easier to use when you can make some assumptions like this.

Promises/A+ 上有一个已关闭的问题 GitHub 存储库与此相关的讨论.

There is a closed issue on the Promises/A+ GitHub repo with discussion about this.

这篇关于Promise/A+ 规范第 2.2.4 条背后的意图是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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