Promise chaining and error handling - javascript

I'm trying to understand chaining and error handing with promises. Here I have some promise chained.
return ad_fetcher.getAds(live_rail_url, ad_time, req.sessionID)
.spread(generator.playlist_manipulate) // returns Promise.resolve([data, anotherData])
.then(client.incrAsync(config.channel_name + ":ad_hits", "vdvd")) // FOCUS HERE
.then(function() {
console.log("AD FETCHED AND PLAYLIST GENERATED.");
res.send(generator.generate_regular(config.default_bitrate));
})
.catch(function(err) {
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
console.log("!!! AD FETCHER - THERE WAS AN ERROR:!!!!!!!!!!!");
client.sadd(config.channel_name + ":ad_errors", err);
client.incr(config.channel_name + ":ad_errors:count");
console.log(err);
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
res.send(generator.generate_regular(config.default_bitrate));
});
Now here at the line client.incrAsync(config.channel_name + ":ad_hits", "vdvd") I intendedly write wrong syntax to see if error is caught by .catch. But when I run this, I get this:
Unhandled rejection Error: ERR wrong number of arguments for 'incr'
command
But when I change usage of that promise to this:
.
.
.then(function() {
return client.incrAsync(config.channel_name + ":ad_hits", "vdvd");
})
.
.
Error is caught pretty well. It's not "unhandled" anymore.
I don't understand this behavior. Doesn't incrAsync return a promise so it's errors should be caught by the .catch at the end of the chain?
Note: I promisified redis client, no doubt with that.
Thanks!

When you chain promises, you invoke the next function in the chain with the result of the previous function.
However, you're invoking your function that returns a promise directly. So unless invoking that function returns a function that returns a Promise, you're not correctly chaining.
So either of these would work:
.spread(generator.playlist_manipulate) // returns Promise.resolve([data, anotherData])
.then(client.incrAsync) // this function will receive [data, anotherData]
Or, as you used in your question, an anonymous function:
.spread(generator.playlist_manipulate) // returns Promise.resolve([data, anotherData])
.then(function() { // this function receives [data, anotherData] but throws it away
// this Promise is "subsumed" by the Promise chain. The outer Promise BECOMES this Promise
return client.incrAsync(config.channel_name + ":ad_hits", "vdvd");
})
Because otherwise, what you've written is basically this:
.then(function)
.then(Promise)
.then(function)
But you need to pass functions to .then, not Promises, if you want them to be handled by your .catch block at the end.

Related

Passing results via promise chain not accessible?

According to my code below i am chaining all the data until the end where i wish to render the data to the view however using the .catch i found that summoner is not accessible at the final function.
getSummonerData(req.params.playerName)
.then(function(summoner) {
return getMatchIds(summoner[0].id);
})
.then(function(matchIds) {
return getGameData(matchIds);
})
.then(function(gameData) {
res.render('profile', {player:summoner, games:gameData});
})
.catch(function(e) {
console.log(e);
});
In your code, summoner is only accessible to the then callback containing your call to getMatchIds, not elsewhere. To be accessible later, you'd have to either 1) Return it from that then callback along with the game data, or 2) Nest the then callbacks that need it inside that callback.
The latter is probably the easier one:
getSummonerData(req.params.playerName)
.then(function(summoner) {
return getMatchIds(summoner[0].id)
.then(function(matchIds) {
return getGameData(matchIds);
})
.then(function(gameData) {
res.render('profile', {player:summoner, games:gameData});
});
})
.catch(function(e) {
console.log(e);
});
I am not sure what you mean by "promise function". I am guessing you are not aware that 'then' and 'catch' always return promises. That is why you can chain them. Each 'then' or 'catch' is a method of the promise returned by its predecessor. Those chained promises are later resolved or rejected depending on what happens to their predecessors.
I assume your last function 'res.render(...)' returns the value you want to see. Then the promise 'then(render(...))' will become resolved with the value received from 'res.render(...)'.
So that is what 'catch' will be working with: a resolved promise with the value you want to see. But 'catch' only fires its function with a 'rejected' promise. You need a 'then' instead.

Why do both Promise's then & catch callbacks get called?

I have the following code and when it's executed, it returns both "rejected" and "success":
// javascript promise
var promise = new Promise(function(resolve, reject){
setTimeout(function(){reject()}, 1000)
});
promise
.catch(function(){console.log('rejected')})
.then(function(){console.log('success')});
Could anyone explain why success is logged?
The then callback gets called because the catch callback is before it, not after. The rejection has already been handled by catch. If you change the the order (i.e. (promise.then(...).catch(...))), the then callback won't be executed.
MDN says that the .catch() method "returns a new promise resolving to the return value of the callback". Your catch callback doesn't return anything, so the promise is resolved with undefined value.
Could anyone explain why success is logged?
In short: a .then following a .catch in a Promise chain will always be executed (unless it itself contains errors).
The theoretical explanation
Your code is actually just a Promise chain which is first executed synchronously setting it up to complete asynchronously afterwards. The Javascript engine will pass on any reject() or Error to the first .then down the chain with a reject callback in it. The reject callback is the second function passed to a .then:
.then(
function (){
//handle success
},
function () {
//handle reject() and Error
})
The use of .catch is just syntactic suger for:
.then(null, function () {
//handle reject() or Error
})
Each of the .then's automatically returns a new Promise which can be acted upon by subsequent .then's (or .catch's which are also .then's).
Visualizing the flow of your promise chain
You can visualize the flow of your code with the following example:
var step1 = new Promise (function (resolve, reject) {
setTimeout(reject('error in step1'), 1000);
})
var step2 = step1.then(null, function () {
// do some error handling
return 'done handling errors'
})
var step3 = step2.then(function () {
// do some other stuff after error handling
return 'done doing other stuff'
}, null)
setTimeout (function () {
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Asynchronous code completed')
console.log();
}, 2000);
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Synchronous code completed')
console.log();
which at runtime will result in the following output in the console:
step1: Promise { <rejected> 'error in step1' }
step2: Promise { <pending> }
step3: Promise { <pending> }
Synchronous code completed
step1: Promise { <rejected> 'error in step1' }
step2: Promise { 'done handling errors' }
step3: Promise { 'done doing other stuff' }
Asynchronous code completed
For those who had a successfully resolved promise and a chain ordered like .then > .catch, but still had both your then and catch called, it may be because your then had an error-throwing bug that you can't see unless you explicitly console the error in your catch. That's one of my pet-peeves with Promises absorbing errors even in strict mode.
const promise = new Promise(resolve => resolve())
.then(() => {
console.log('then');
not.defined = 'This causes the catch to fire even though the original promise resolved successfully.';
})
.catch((e) => {
console.log('catch');
// console.error(e);
});
For me catch() was being called after a succesful promise, and no errors in .then().
The reason was, that I listened to a value that changes with the successful promise, and ran a method.
This method was throwing a silent error, because it was being counted as part of the promise.
Similar to #Timar, For me the reason catch was being called is that "then" contains an exception code. so after executing "then" normally and when it reaches the exception code, it handles the exception in "catch" xD

Promises: is .done() executed always even if .catch() is?

My Promise issue
I am new to Promises and I've been reading the Q Documentation, where it says:
When you get to the end of a chain of promises, you should either return the last promise or end the chain.
I have defined a Promise in my code the Q.Promise way, with the following console.logs to log out an execution trace:
function foo(){
return Q.Promise(function(resolve, reject) {
doSomething()
.then(function() {
console.log('1');
return doSomething1();
})
.then(function() {
console.log('2');
return doSomething2();
})
.then(function() {
console.log('3');
return doSomething3();
})
.catch(function(err) {
console.log('catch!!');
reject(err);
})
.done(function() {
console.log('done!!');
resolve();
});
});
}
In case every doSomethingN() executes correctly, everything works as intended and I get the expected trace:
1
2
3
done!!
But in case any of the doSomethingN() fails:
foo() works correctly, because the error function callback is the one that runs whenever a reject(err) occurs:
foo().then(function() { /* */ }, function(err) { /* this runs! */ });
And I get the following trace (ie. when doSomething1() fails):
1
catch!!
done!!
My question
What I thought at first was the following:
Okay, let's handle the chaining success and failure in both: .done() and .catch() methods. If everything goes well .done()'s callback will be executed and the promise will be resolved. In case there's an error at any point, .catch()'s callback will be executed and the promise will be rejected - and because of that, done() won't be executed.
I think I am missing something about how the .done() works... because by having a look at my logging trace, I realized that .done() seems to be executing always - whether there is an error and .catch() is executed or not - and that is what I wasn't expecting.
So, after that, I removed .done()'s callback and now foo():
works if there's an error during the chain execution
does not work if everything works correctly
What should I reconsider and how could/should I make it work?
catch(cb) is just an alias for then(null, cb), and you've actually fixed an error in catch, so flow naturally turned to success result in done.
If you want to just decorate the error in catch, you should rethrow the error afterwards, e.g. proper passthru may look as:
catch(function (err) {
console.log(err);
throw err;
});
Still your example doesn't make much sense. You should never use done, when you return a promise. If you want to resolve initialized promise with internally created chain of promises, you should just resolve it as:
resolve(doSomething()
.then(function() {
console.log('1');
return doSomething1();
})
....
.then(function() {
console.log('N');
return doSomethingN();
}));
There's no need for internal error handling, leave that to consumer of promise which you return.
And other point. If when creating new promise you know it will be resolved with other one, then there's no logical reason to create such promise, just reuse one you planned to resolve with. Such error was also coined as deferred anti-pattern
You should consider doing this:
function foo() {
// Calling .then() on a promise still return a promise.
// You don't need Q.Promise here
return doSomething()
.then(function(doSomethingResult) {
console.log('1');
return doSomething1();
})
.then(function(doSomething1Result) {
console.log('2');
return doSomething2();
})
.then(function(doSomething2Result) {
console.log('3');
return doSomething3();
});
}
foo()
.then(function(fooResult) {
console.log(fooResult); // fooResult should be what is returned by doSomething3()
})
.catch(function(err) {
console.error(err); // Can be thrown by any
})
.done(function() {
console.log('I am always executed! error or success');
});
If you want to return a promise, in most cases it does not make much sense to use catch (unless you want to recover potential errors). It never make sense to use done in a method returning a promise. You would rather use these methods at the very end of the chain.
Notice that doSomethingX() can return either a value, or a promise, it will work the same.
You can make it work by resolving promise in your last then callback.
function foo(){
return doSomething()
.then(function() {
console.log('1');
return doSomething1();
})
.then(function() {
console.log('2');
return doSomething2();
})
.then(function() {
console.log('3');
return doSomething3();
})
}
Consider using bluebird for promises. It has many useful features as compared to any other promise library. You may find it difficult to begin it, but once you get hold of it you're going to love it.

Recovering from rejected promises in JS

I'm using native promises (mostly) and attempting to recover from an error and continue executing the promise chain.
Effectively, I'm doing this:
REST query to see if ID exists. Note that this returns a jquery deferred.
.then (success means ID exists, so fail and stop)
(fail means ID does not exist, so continue creating ID)
.then (create the ID record and send to the server)
I return a Promise.resolve() from my rejected function, which should cause the success part of the next .then to execute. It does not. I've tried this on Chrome and Safari.
Note that the first promise is actually a query deferred, but according to this page (http://api.jquery.com/deferred.then/), deferred.then() returns a promise object. So adding an extra .then should covert to native promises.
To make it clearer - here's the pseudocode:
promise = $.ajax(url);
promise = promise.then(); // convert to promise
promise.then(function() { cleanup(); return Promise.reject(); },
function(err) { return Promise.resolve(); });
.then(function() { createIdentityDetails(); });
.then(function() { sendIdentityDetails(); });
Note that I want to FAIL when the ajax returns success, and I want to
continue processing when the ajax call fails.
What happens is that the FAIL functions for all subsequent .then portions execute. That is, my return Promise.resolve() doesn't work - which is (I think) in violation of the spec.
I'd appreciate any feedback on how I can deal with and recover from errors in long promise chains.
Many thanks for any advice you can provide.
p.s. creating and collecting the full identity information is quite time consuming, so I don't want to do it if the ID exists. Hence I want to check first and fail quickly.
p.p.s I really like the way that promises have unwound these deeply nested async callback chains.
Assuming createIdentityDetails() and sendIdentityDetails() to be promise-returning asynchronous functions ...
If what we see in the question is the entirety of the promise chain, then handling the error condition is simple. It's not necessary to convert success to failure or failure to success, or from one type of promise to another.
$.ajax(url).then(function() {
cleanup();
}, function(err) {
createIdentityDetails()
.then(sendIdentityDetails);
});
This will work regardless of the type of promise returned by createIdentityDetails() jQuery or non-jQuery.
If, however, there's more to it, eg a caller function needs to be informed of the outcome, then you need to do more, and it depends on how you want the possible outcomes to be reported.
Report 'ID already exists' as failure and 'new ID created' as success
This is what the question suggests
function foo() {
return $.ajax(url).then(function() {
cleanup();
return $.Deferred().reject('failure: ID already exists');
}, function(err) {
return createIdentityDetails()
.then(sendIdentityDetails)
.then(function() {
return $.when('success: new ID created');
});
});
}
Report both types of outcome as success
This seems more sensible as the handled error will be reported as success. Only unpredicted, unhandled errors will be reported as such.
function foo() {
return $.ajax(url).then(function() {
cleanup();
return 'success: ID already exists';
}, function(err) {
return createIdentityDetails()
.then(sendIdentityDetails)
.then(function() {
return $.when('success: new ID created');
});
});
}
Whichever reporting strategy is adopted, it matters very much what type of promise createIdentityDetails() returns. As the first promise in the chain it determines the behaviour of both its chained .thens.
if createIdentityDetails() returns a native ES6 promise, then no worries, most flavours of promise, even jQuery, will be assimilated.
if createIdentityDetails() returns a jQuery promise, then only jQuery promises will be assimilated. Therefore sendIdentityDetails() must also return a jQuery promise (or an ES6 promise which must be recast into jQuery with $.Deferred(...)), as must the final success converter (as coded above).
You can see the effects of mixing jQuery and ES6 promises in these two ways here. The first alert is generated by the second block of code, and is not what is expected. The second alert is generated by the first block and correctly gives the result 98 + 1 + 1 = 100.
promise = promise.then(); // convert to promise
Huh? A promise returned by $.ajax is already a promise.
promise.then(function() { cleanup(); return Promise.reject(); },
function(err) { return Promise.resolve(); });
The problem with this is that jQuery is not Promises/A+ compatible, and fails to adopt promises/thenable from other implementations than its own. You would have to use $.Deferred here to make this work, like
promise.then(function() { cleanup(); return $.Deferred().reject(); },
function() { return $.when(); }); // or return $.Deferred().resolve();
That is, my return Promise.resolve() doesn't work - which is (I think) in violation of the spec.
Indeed it is. However, jQuery is known for this, and they won't fix it until v3.0.
To get the native Promise library you want to use working, you will need to avoid jQuery's then. This can easily be done:
var $promise = $.ajax(url);
var promise = Promise.resolve($promise); // convert to proper promise
promise.then(function() {
cleanup();
throw undefined;
}, function(err) {
return undefined;
})
.then(createIdentityDetails)
.then(sendIdentityDetails);
It seems that JQuery promises do not permit you to change a failure to a success. If, however, you use native promises, you can.
For example:
Promise.resolve()
.then(function() {console.log("First success"); return Promise.reject(); },
function() { console.log("First fail"); return Promise.resolve(); })
.then(function() {console.log("Second success"); return Promise.reject(); },
function() { console.log("Second fail"); return Promise.resolve(); })
.then(function() {console.log("Third success"); return Promise.reject(); },
function() { console.log("Third fail"); return Promise.resolve(); })
Here I return a reject from the first success handler. In the second failure handler I return a resolve. This all works as expected. The output is (Chrome):
First success
Second fail
Third success
It turns out the proper way to deal with jQuery deferreds and promises is to cast them:
var jsPromise = Promise.resolve($.ajax('/whatever.json'));
(from http://www.html5rocks.com/en/tutorials/es6/promises/).
This works nicely, so if you change the initial line above to:
Promise.resolve($.ajax("this will fail"))
...
you correctly get:
First fail
Second success
Third fail
Bottom line... cast deferred to promise asap, then everything seems to work right.
Hopefully this will clear things up a bit, you had a couple of stray ; and you're doing things you don't really need to do in the then functions
firstly, I'm sure you DO NOT want the
promise = promise.then();
line, the code would look like this
promise = $.ajax(url);
promise.then(function() {
cleanup();
throw 'success is an error'; // this is equivalent to return Promise.reject('success is an error');
}, function(err) {
return 'failure is good'; // returning here means you've nullified the rejection
}) // remove the ; you had on this line
.then(function() { createIdentityDetails(); }) // remove the ; on this line
.then(function() { sendIdentityDetails(); }) // remove the ; on this line
.catch(function(err) { }); // you want to catch the error thrown by success

Is there a good way of short circuiting Javascript promises?

I'm a bit of a novice with promises/Deferreds. Is there a good pattern to handle the case where one might want to short circuit a chain of promises, for both success and error cases? In the error situation, I know you can chain a .then(null, function(error) {}) to the end and catch an error from any of the previous thens, but what if you want to handle an error in a more custom way and terminate? Would you specify a 'type' of error in an earlier error handler and return it via a new promise, to be handled or skipped in the final error handler? And what about a success case, where you want to terminate earlier in the chain (only conditionally firing off any later then's)?
Typically, the promise chain starts with a call to some asynchronous function as such:
var promise = callAsync();
If you are chaining a second async call, you probably do something like this:
var promise = callAsync()
.then(function(){
return callOtherAsync();
})
.then(function(){
return callSuccessAsync();
}, function(){
return callFailAsync();
});
As a result of chaining, promise now contains the final promise which completes when callFinalAsync()'s promise completes. There is no way to short circuit the final promise when using this pattern - you can return a failed promise along the way (for instance, rather than returning the result of callOtherAsync) but that requires the failed promise to progress through the chain (thus causing callFailAsync to be called).
You can always fulfill or reject the promise from within the callbacks as such
var promise = callAsync()
.then(function(){
if(fail){
promise.reject();
//no way to halt progression
}else{
return callOtherAsync();
}
})
.then(function(){
return callSuccessAsync();
}, function(){
return callFailAsync();
});
however, this will not prevent calls to callFailAsync(). Some Promise/A implementations expose a stop method for just this purpose. With stop, you could do this:
var promise = callAsync();
.then(function(){
if(fail){
this.stop();
promise.reject();
}else{
return callOtherAsync();
}
})
.then(function(){
return callSuccessAsync();
}, function(){
return callFailAsync();
});
Which depends on having access to the intermediate promise with this. Some Promise implementations forbid that (forcing this to be window/null/etc), but you can deal with that with a closure.
TL;DR: Promise/A spec doesn't provide a chain short circuit function, but it's not hard to add one.
not sure about jQuery but at least in any Promises/A+ you can just throw:
.then(function() {
if (skip) {
throw new Error("skipping");
}
})
//Chain of thens
.then(...)
.then(...)
.then(...)
.then(...)
.catch(function(){
//skipped here
});
I assume your use case looks like:
promise
.then(a)
.then(b); // We want to have an option to break here
.then(c)
.done(d)
Logical way to handle this is:
promise
.then(a)
.then(function (result) {
if (something) throw new Error("Do not proceed!");
return b(result).then(c).then(d);
}).done();
If you don't like nesting, you may compose b(result).then(c).then(d) as outer function.
I had this exact problem in my application, and achieved short-circuit/cancellation through use of a simple cancellation token object that can be checked for in a Promise's exception/rejection handler callback. Maybe not the most elegant solution, but seems to work well enough without the need for additional libraries or alternate/non-standard Promise implementations
const cancellationToken = {};
somePromiseReturningMethod(...)
.then(doSomething)
.then(doSomethingElse)
.catch(err => {
if (err === cancellationToken)
{
// handle cancellation here and return
}
// handle "regular" errors here (show/log a message, etc)
});
function doSomething(dataFromPromise)
{
// check for whatever condition should result in cancellation/short-circuit
if (...)
{
return Promise.reject(cancellationToken);
}
// carry on as normal...
}

Categories

Resources