What is the intention behind clause 2.2.4 of Promise/A+ spec?

五迷三道 提交于 2019-11-26 08:37:13

问题


Clause 2.2.4 of the promise/a+ spec says:

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

Then in the notes it states that:

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.

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?


回答1:


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;

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.

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



来源:https://stackoverflow.com/questions/36932244/what-is-the-intention-behind-clause-2-2-4-of-promise-a-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!