promise-it-wont-hurt
promise-it-wont-hurt copied to clipboard
A problem proposal: fullfilling rejections
Hi. I was just working with mongodb
and I sidetracked to thinking on promises and understanding a little more of them. After having solved this workshop (which was great), I was tinkering with a concept on the Promises/A+ spec that we can add as a new exercise. Consider the following code snippet.
var Q = require('q');
var deferred = Q.defer();
var promise = deferred.promise;
var promise2 = promise.then(undefined, function savior(rejection) {
console.log("Im the savior, who received: " + rejection);
return {
then: function(resolve, reject) {
resolve("A saved rejection");
}
};
});
promise2.then(function(value) {
console.log("The promise 2 was fullfilled with: " + value);
}, function(reason) {
console.log("The promise 2 was rejected with: " + reason);
});
deferred.reject("A rejection reason");
The output of this program would be
Im the savior, who received: A rejection reason
The promise 2 was fullfilled with: A saved rejection
So, I think the magic to show on this program is in receiving a rejected promise (the promise
promise) and then making it's then
method return a fullfilled promise (the promise2
promise) with the usage of returning thenables. Somehow the curiosity got me high this night to think on this kind of things (hey, a rime).
A problem on exercising this concept should be a nice addition.
Just experimenting and forgot a simpler way: changing the return line with just return 'A saved rejection';
works too.
PD: just using return;
works too, but then the promise is fulfilled with undefined
.
Hmm I haven't thought about that. I guess this is a pretty good idea, even though your implementation is a bit odd looking :)
That's the comment for. So simplifying a little:
var Q = require('q');
var deferred = Q.defer();
var promise = deferred.promise;
var promise2 = promise.catch(function savior(rejection) {
console.log("Im the savior, who received: " + rejection);
return "A saved rejection";
});
promise2.then(function(value) {
console.log("The promise 2 was fullfilled with: " + value);
}, function(reason) {
console.log("The promise 2 was rejected with: " + reason);
});
deferred.reject("A rejection reason");
Yep. There have been a lot of changes done to promise-it-wont-hurt recently: https://github.com/stevekane/promise-it-wont-hurt/issues/46#issuecomment-172731538. I will take this as one of my TODOs.
On a side note, it would really help us if you could find time to translate (or to correct) a few strings into Spanish: https://github.com/stevekane/promise-it-wont-hurt/blob/master/i18n/es.json I'm still learning Spanish and unfortunately my accent and vocabulary is distinctively estadounidense :)
I could do something about it the wednesday or the weekend to feel helpful ;)
Oh what the heck, I peeked at it, seemed easy, and I just did it on #62