When or who does pass resolve and reject functions to JS promises?

The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

Nobody.

The functions are passed by the promise constructor.

They are passed to the function which you pass as the first argument to the promise constructor.


The Promise constructor is initialized with a callback, and the constructor passes reject and resolve as parameters when the callback is called.

Here is a simple demo:

class PromiseDemo {
  constructor(cb) {
    cb(this.resolve.bind(this), this.reject.bind(this));
  }
  
  resolve(d) {
    console.log('resolve', d);
  }
  
  reject(d) {
    console.log('reject', d);
  }
}

new PromiseDemo((resolve, reject) => {
  Math.random() > 0.5 ? resolve('1') : reject('1');
});

I had the same problem in understanding Promises.You need to look at the process of promise creation carefully. when you write var promise= new Promise(function(resolve,reject){...})

you are actually invoking constructor of Promise class or creating an object of Promise class. Now Promise constructor requires a function callback. Now resolve and reject are just function arguments and not any other values. You can write anything in place of resolve or reject like resolveHandler or rejectHandler.

These resolve or reject are nothing but the function callback that Promise calls when Promise is executed.

Now resolve is called when Promise is executed successfully and reject is called when promise is executed with some error or unsuccessfully .

The argument with which resolve is called can be accessed inside then like this

getImage().then(function(valueSentInResolve){ console.log('')})

The argument with which reject is called can be accessed inside catch like this

getImage().then(function(valueSentInResolve)
  {//..do something}
).catch(function(errorSentInReject){
  console.log('error',errorSentInReject )
})

I hope that helps.Let me know if I said anything wrong.