Why do Promise libraries use event loops?

后端 未结 3 903
天命终不由人
天命终不由人 2020-12-15 11:43

Considering the following JavaScript code:

var promise = new Promise();
setTimeout(function() {
    promise.resolve();
}, 10);

function foo() { }
promise.th         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-15 12:02

    All promise implementations, at least good ones do that.

    This is because mixing synchronicity into an asynchronous API is releasing Zalgo.

    The fact promises do not resolve immediately sometimes and defer sometimes means that the API is consistent. Otherwise, you get undefined behavior in the order of execution.

    function getFromCache(){
          return Promise.resolve(cachedValue || getFromWebAndCache());
    }
    
    getFromCache().then(function(x){
         alert("World");
    });
    alert("Hello");
    

    The fact promise libraries defer, means that the order of execution of the above block is guaranteed. In broken promise implementations like jQuery, the order changes depending on whether or not the item is fetched from the cache or not. This is dangerous.

    Having nondeterministic execution order is very risky and is a common source of bugs. The Promises/A+ specification is throwing you into the pit of success here.

提交回复
热议问题