0

Im new to js and getting hard time understanding the promises, and nested promises. why is it that when my promise return an error, it still load the nested .then(). here is my sample code.

   firstFunction()
   .then(success(){
   //some statement
   return secondFunction(); 
   }, error(err){
   //logging the err. 
   })
  .then(success(){
    //some statement for secondFunction
   },error(err){
    //logging error for second function
   })

when my firstFunction is okay, they work fine, load firstfunction .then, followed by secondFunction.then, but when first function fails, it goes to its :error(err) function, but still executes my code in my secondFunction.then() ?

Joe
  • 83
  • 1
  • 1
  • 8

1 Answers1

0

When you have an error handler and you want the error to continue to propagate, you have to either return a reject promise from the error handler or throw an error. If you don't do either of those, then the error is considered "handled" and the promise state becomes resolved, not rejected.

So, after logging the error, you need to throw the error again.

firstFunction().then(success(){
   //some statement
   return secondFunction(); 
}, error(err){
   //logging the err.
   console.log(err);
   throw err;                  // <== keep the promise rejected
}).then(success(){
    //some statement for secondFunction
},error(err){
    //logging error for second function
});

FYI, this works just like try/catch. If you catch the error and don't rethrow, then the exception is considered "handled" and normal execution continues. Promises work the same way with their error handlers.

jfriend00
  • 683,504
  • 96
  • 985
  • 979