Search code examples
javascriptes6-promise

JavaScript: Promise callback execution


I need know to whether a Promise is executed synchronously or asynchronously. According to the mozilla docs, the promise callback - executor function is executed immediately by the Promise implementation.

But it does not seem to work like that to me according to the following code-

let myPromise = new Promise((resolve, reject) =>
    resolve("Resolved from the promise");
);

myPromise.then(console.log);

console.log("After resolving the promise");

The log in the promise then handler gets printed after the log on the last line. Why it is executing like asynchronous way. Is I am missing anything?


Solution

  • The promise executor function is the function you pass to new Promise. It is executed synchronously so it can start whatever asynchronous process the promise represents.

    The callbacks you attach with then, catch, and finally are always called asynchronously, whether the promise is already settled or not.

    So in your example, console.log("After resolving the promise"); is called before the console.log you've passed to then.

    Here's an example showing that more clearly:

    let myPromise = new Promise((resolve, reject) => {
        console.log("In the executor function");
        resolve("Resolved from the promise");
    });
    myPromise.then(result => {
        console.log("In the fulfillment handler: " + result);
    });
    
    console.log("After resolving the promise");

    The output of that is:

    In the executor function
    After resolving the promise
    In the fulfillment handler: Resolved from the promise
    

    Notice that "In the executor function" is logged before "After resolving the promise" because the executor is called synchronously, but "In the fulfillment handler: Resolved from the promise" is afterward because that's called asynchronously.