I have begun 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 function to a promise constructor ?
See this example of Promise:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
Now who does pass resolve and reject methods, as my understanding of javascript says to me that this script will throw unknown variable errors as resolve and rejects are not defined?
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
console.log('Error loading ' + errorurl)
})
Now you see a method like the above, the only way these methods(resolve and reject) are passed are via then and catch as used in above method call to getImage.
then() method should be called on the promise object to handle a result (resolve) or an error (reject). It accepts two functions as parameters. Usually, the . then() method should be called from the consumer function where you would like to know the outcome of a promise's execution.
A Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. It may be either fulfilled or rejected — for example, resolving a rejected promise will still result in a rejected promise.
A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.
The Promise. reject() method returns a Promise object that is rejected with a given reason.
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With