我对 javascript 嵌套承诺有一些问题

I have some problems with javascript nested promises

我是 js 新手,很难理解承诺和嵌套承诺。为什么当我的 promise return 出错时,它仍然加载嵌套的 .then()。这是我的示例代码。

   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
   })

当我的 firstFunction 没问题时,它们工作正常,加载 firstfunction.then,然后是 secondFunction.then,但是当第一个函数失败时,它会转到它的 :error(err) 函数,但仍然执行我的代码在我的 secondFunction.then() ?

当您有错误处理程序并且希望错误继续传播时,您必须 return 拒绝来自错误处理程序的承诺或抛出错误。如果您不执行其中任何一项,则错误被视为“已处理”并且承诺状态变为已解决,而不是被拒绝。

所以,记录错误后,需要再次抛出错误。

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
});

仅供参考,这就像 try/catch 一样工作。如果您捕获到错误并且没有重新抛出,则该异常被视为“已处理”并继续正常执行。 Promises 与错误处理程序的工作方式相同。