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
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?
}