I have been studying Promises all day, and had the same question. I finally figured it out.
When you make a Promise object, you give the Promise Constructor an executor
, which can be any function, as long as it has this signature.
anyFunction(resolutionFunction, rejectionFunction){
// typically, some asynchronous operation.
}
So any function with 2 functions as the arguments can be used. The first function is what you call when it works, the second is what you call when it breaks. You can name those functions whatever you want as well.
The Promise Constructor takes the function you pass in and does a few things with it.
- It takes those 2 function arguments and generates a corresponding pair of functions that are "connected" to the Promise object.
- It runs the executor
- It ignores any return value from your executor
Now in your executor function when the promise resolves you call the positionally first function and pass it one value. It will look something like:
resolutionFunction(value)
You may be wondering, where is resolutionFunction
defined? Remember the Promise Constructor defined that function for us. So we can call resolutionFunction
without having to define it ourselves. Behind the scenes, when we call that resolutionFunction
generated by the Promise Constructor, it sets the state of the promise to fulfilled, calls the function inside the promiseObject.then
function, and passes the value into the .then
function so you can use it.
You would call the 2nd positional function if the promise failed and the same things would happen and you could deal with the failure.
This Mozilla Doc on the Promise Constructor was very helpful.
Here is a short examples that shows what I explained above.
function anyFunction(callThisFunctionWhenItWorks, callThisFunctionWhenItBreaks) {
let importantNumber = 10; //change to 11 if you want the promise to reject
if (importantNumber == 10) {
callThisFunctionWhenItWorks('Hooray, success, so we call resolved for the promise.');
} else {
callThisFunctionWhenItBreaks('Boo, rejected because important number is not equal to 10');
}
}
//make a new promise
const examplePromise = new Promise(anyFunction);
//use the promise
examplePromise.then(function(result) {
console.log(result);
}).catch(function (error) {
console.log(error);
})
resolve
andreject
are parameters of the function you pass into thePromise
. ThePromise
itself calls this functions and passes in the two parameters.function cb(resolve, reject) { ... }; new Promise(cb);
– does that help…?resolve
, which then calls yourthen
callback, you could just directly call yourthen
callback. It's essentially the same thing. However, promises enable you to compose (chain) such callbacks in ways that would quickly become very complicated if you just call callbacks directly. Especially if you figure in the complexity of error handling, which promises solve very easily with chainablecatch
callbacks.