Search code examples
javascriptes6-promise

Static methods of Promise constructor


I am inspecting the static methods of Promise constructor. When I console logging Promise constructor properties I see resolve and reject methods:

console.log(Object.getOwnPropertyNames(Promise))
// Array(7) [ "all", "race", "reject", "resolve", "prototype", "length", "name" ]

I wonder are these resolve and reject methods are the same methods that are used in executor as its parameters or these are separate different things:

const myFirstPromise = new Promise((resolve, reject) => {
//   do something asynchronous which eventually calls either:
//
//   resolve(someValue); // fulfilled
//   or
//   reject("failure reason"); // rejected
});

Specification mentions Promise Resolve Functions and Promise.resolve ( x ) which is the %Promise_resolve% intrinsic object. Can someone tell me are these the same?


Solution

  • The properties you see in the output of console.log() are the .resolve() and .reject() properties of the global JavaScript Promise object. You can think them as static class methods of the Promise class.

    They are used to create new Promise objects that are already resolved/rejected:

    const p1 = Promise.resolve(3);
    console.log(await p1);
    // 3
    

    The promise and reject parameters you use in the call:

    const myFirstPromise = new Promise((resolve, reject) => {
       if (rand() < 0.5) {
           resolve(3);
       } else {
           reject(new Error('not today'));
       }
    });
    

    are just function parameters. They can be named however you want; they are visible only in the executor function you pass as argument to the Promise constructor.

    They are not linked or related in any with to Promise.resolve() and Promise.reject().

    The code above can also be written as:

    const f1 = (resolve, reject) => {
       if (rand() < 0.5) {
           resolve(3);
       } else {
           reject(new Error('not today'));
       }
    };
    
    const myFirstPromise = new Promise(f1);
    

    This way it is more clear that resolve and reject are not related to myFirstPromise or to any Promise in any way. They are just local variables of function f1.