javascript - Promise's second .then() not failing -


this question has answer here:

i'm having trouble chaining .then() calls promise. when executing following code:

var prom = new promise(function(resolve, reject) {   //let's fail   reject(error("buuuu!")); });  var thenable =  prom.then(     function(done) {         console.log("first handler: done!: argument: ", done);         return "first then: done";     },     function(fail) {         console.error("first handler: fail!. argument: ", fail);         return "first then: fail";     } ).then(     function(done) {         console.info("second handler: done!.  argument: ", done);     },     function(fail) {         console.error("second handler: fail!.  argument: ", fail);     } ); 

this prints following in console:

first handler: fail!. argument:  error {stack: (...), message: "buuuu!"} second handler: done!.  argument:  first then: fail 


why second then() has done handler called instead of fail one?

is bug chrome? (note i'm interested in google chrome's behavior)

do need resort returning pre-resolved/rejected promises .then handlers?

why second then() has done handler called instead of fail one?

because handled error in first then() of chain already, making promise resolve "first then: fail" string returned it.

is bug chrome?

no, that's how promises supposed work.

do need resort returning pre-resolved/rejected promises .then handlers?

you can that, yes. other ways trigger second fail handler be:

  • simply omit first error handler:

    prom.then(function(done) {     console.log("first handler: done!: argument: ", done);     return "first then: done"; }).then(function(done) {     console.info("second handler: done!.  argument: ", done); }, function(fail) {     console.error("second handler: fail!.  argument: ", fail); }); 
  • or rethrow exception (that's similar returning rejected promise):

    prom.then(function(done) {     console.log("first handler: done!: argument: ", done);     return "first then: done"; }, function(fail) {     console.error("first handler: fail!. argument: ", fail);     throw new error("first then: fail"); // or: throw fail;     // alternatively, can return rejected promise:     return promise.reject(new error("first then: fail")); }).then(function(done) {     console.info("second handler: done!.  argument: ", done); }, function(fail) {     console.error("second handler: fail!.  argument: ", fail); }); 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -