Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 296
Cui Pengfei 崔鹏飞 Avatar asked Apr 29 '16 07:04

Cui Pengfei 崔鹏飞


1 Answers

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.

like image 183
noppa Avatar answered Sep 30 '22 18:09

noppa