Reputation: 1101
What is the difference between
resolve
and onFulfilled
in javascript promises ?
Similarly, what is the difference between
reject
and onRejected
?
In simple words, I would just ask how does onsuccess callback of Promise.then(onsuccess, onreject) differs from Promise.resolve ()?
I am reading Javascript with Promises by Daniel Parker. The book has mentioned both of them but I have not realized the difference between two yet.
While describing then in promises:
promise.then
promise.then([onFulfilled], [onRejected]) returns promise
The promise.then() method accepts an onFulfilled callback and an onRejected callback. People generally register onRejected callbacks using promise.catch() instead of passing a second argument to then . The function then returns a promise that is resolved by the return value of the onFulfilled or onRejected callback. Any error thrown inside the callback rejects the new promise with that error.
Also,
Promise.resolve
Promise.resolve([value|promise]) returns promise The Promise.resolve() function is a convenience function for creating a promise that is already resolved with a given value. If you pass a promise as the argument to Promise.resolve(), the new promise is bound to the promise you provided and it will be fulfilled or rejected accordingly.
Code:
function settled(promises) {
var alwaysFulfilled = promises.map(function (p) {
return p.then(
function onFulfilled(value) {
return { state: 'fulfilled', value: value };
},
function onRejected(reason) {
return { state: 'rejected', reason: reason };
}
);
});
return Promise.all(alwaysFulfilled);
}
};
Upvotes: 5
Views: 6018
Reputation: 1
simply put
when a promise is resolved any current or future onFullfilled functions will be called with the parameter to that function being the value of the resolve function
similarly with reject/onRejected
Upvotes: 2