I have begin learning javascript promises. But I just can\'t understand the concept of promises. The thing that bothers me most is who is passing the Resolver and Reject fun
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');
});
does this make sense? This explanation could be completely incorrect!!
We provide the logic which should run asynchronously. The logic should accept 2 functions, resolve
and reject
. The reference of these functions is provided by Promise
. These functions should be called by our logic when we have the final value or error. The Promise
created initially is in Pending
state. Calling resolve
and reject
changes the state to Fulfilled
or Rejected
respectively.
executeFunction(res,rej) = {
do some op, say DB query.
if (success) res(value) //executeFunction uses the resolving functions to change state of the Promise. Calling res fulfills the promise with value
if (fail) rej(reason)//executeFunction uses the resolving functions to change state of the Promise. Calling rej rejects the promise with reason
}
Rather than calling executeFunction
directly (which would make the call synchronous), we create a Promise will will run the executeFunction
code in a separate thread (asynchronously) let p = Promise(executeFunction(res,rej));
. We get back a reference of the Promise.
My guess is that internally in the Promise
, the following happens
Promise(e(res,rej)) = {
// the Promise's constructor creates a new promise, initially in the pending state. It calls `e` (the executeFunction function) and provides references to the resolving functions to it that can be used to change its state.
state = pending;
e(_res,_rej); //starts my op. asynchronously (a new thread). Reference to resolving functions, _res, _rej is provided. _res and _rej are Promise's internal functions (see below)
//constructor doesn't return till the async thread finishes
}
_res (value){ //Promise's internal method
//probably sets the state of promise to Fulfilled and store the result of the Promise
state = fulfilled
resolvedValue = value;
}
_rej {//Promise's internal method
probably sets the state of promise to Rejected and store the result of the Promise
state = rejected
resolvedValue = error;
}
Creating the Promise
starts the execution of the code asynchronously. Now we are interested in knowing what is the result of executeFunction
(we don't care when executeFunction
finishes). To do this, we call then
of the Promise
p
. then
takes two optional arguments and registers them as callbacks. I am not sure when and who calls these callbacks. I know that then
returns another Promise
but I am not able to understand how that works
then(executeFnIfPromiseResolved, executeFnIfPromiseRejected):Promise {
register executeFnIfPromiseResolved as callback
register executeFnIfPromiseRejected as callback
//NOT SURE WHO AND WHEN THE CALLBACKS ARE CALLED
//then needs to return Promise. What would be the executor function of that Promise?
}
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.
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 as passed to the function you pass as the first argument to the promise constructor.
The promise library creates and passes those functions, along with all the other metadata needed to track the promise and record completion, store state and progress, cancel it, etc.
The folks behind Bluebird have published some info on how the library works internally, and you can see more in the Bluebird source.