javascript - Promise chaining and error handling -


i'm trying understand chaining , error handing promises. here have 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 , playlist generated.");             res.send(generator.generate_regular(config.default_bitrate));             })         .catch(function(err) {             console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');             console.log("!!! ad fetcher - there 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 @ line client.incrasync(config.channel_name + ":ad_hits", "vdvd") intendedly write wrong syntax see if error caught .catch. when run this, this:

unhandled rejection error: err wrong number of arguments 'incr' command

but when change usage of promise this:

. .     .then(function() {         return client.incrasync(config.channel_name + ":ad_hits", "vdvd");     }) . . 

error caught pretty well. it's not "unhandled" anymore.

i don't understand behavior. doesn't incrasync return promise it's errors should caught .catch @ end of chain?

note: promisified redis client, no doubt that.

thanks!

when chain promises, invoke next function in chain result of previous function.

however, you're invoking function returns promise directly. unless invoking function returns function returns promise, you're not correctly chaining.

so either of these work:

.spread(generator.playlist_manipulate) // returns promise.resolve([data, anotherdata]) .then(client.incrasync) // function receive [data, anotherdata] 

or, used in question, anonymous function:

.spread(generator.playlist_manipulate) // returns promise.resolve([data, anotherdata]) .then(function() { // function receives [data, anotherdata] throws away     // promise "subsumed" promise chain. outer promise becomes promise     return client.incrasync(config.channel_name + ":ad_hits", "vdvd"); }) 

because otherwise, you've written this:

.then(function) .then(promise) .then(function) 

but need pass functions .then, not promises, if want them handled .catch block @ end.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -