Search code examples
javascriptnode.jspromisees6-promise

Does Promise resolution start the moment the promise is created?


In the following code, I noticed that the promise was starting to get resolved the moment getProm() was called(I could notice the delay of 5 seconds on running the code).

I want to confirm whether promise is resolved immediately on creation or only in the following 2 cases. 1) Promise is resolved only when we do Promise.resolve explicitly 2) we make use of .then keyword

function getProm(){
    var prom1 = new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve("Promise is resolved")
        },5000)
    })
    return prom1
}
var mypromise = getProm()

Solution

  • There are three moments to distinguish:

    • The moment the callback is called that you pass to new Promise: the so-called promise constructor callback. This is immediate: it will execute before any other code that follows the new Promise expression. In your case, it means setTimeout is executed immediately.

    • The moment the promise resolves. This happens when the resolve or reject functions are called that are provided to the promise constructor callback. In your case this happens after a delay of 5 seconds.

    • Detection of a resolved promise. This always happens asynchronously: with ES6 promises you cannot detect that a promise has resolved synchronously, even if the code calls resolve without delay. You detect resolution with a then callback (or await). This callback is not called before the current call stack has ran to completion and is emptied. Whether you detect such resolution or not, this does not delay the actual resolution of the promise. If you would execute a then after a 10 minute delay, it would trigger the then callback in the next microtask, even though the promise had already been resolved long ago. You can have several then calls on the same promise: they will all trigger their callbacks.