Search code examples
javascriptpromisespecifications

Specs about eager evaluation of Promise callbacks


Is there a spec / implementation detail on how "eager" is the evaluation of the callbacks of a promise? I mean, let's say that I have

var promise = new Promise((resolve) => {
   resolve()
});

console.log(promise); // there is no public field '<state>', but you can see it in the console of the dev tools

I see that promise is already fulfilled; I was expecting that the Promise internal implementation would call the resolve callback on an following time, leaving a "time window" with promise still unfulfilled.

Is this "eager" evaluation of the resolve callback "by design"? Is this just an implementation detail?


Solution

  • The callback passed to the Promise constructor is executed synchronously by that constructor. So when the new operator returns the constructed object, the callback has already run.

    This is by the ECMA Script specification. The procedure for new Promise(excecutor) describes in step 9 that the executor is called and in step 11 that the constructed promise object is returned.

    Mozilla Contributors write:

    Syntax

    new Promise(executor)
    

    Parameters

    executor
    

    A function to be executed by the constructor, during the process of constructing the new Promise object.

    The constructor callback function is typically used to initiate an asynchronous process (by relying on an asynchronous API, like setTimeout), which can resolve the promise at a time that the constructor callback has already returned.

    function executor(resolve) { 
        setTimeout(resolve, 100);
    }
    
    var promise = new Promise(executor);
    

    In your example, that callback does not rely an such asynchronous API, but synchronously calls the resolve callback. That means that when the constructed promise object is assigned to your promise variable, that promise is already in a fulfilled state.