【问题标题】:I have some problems with javascript nested promises [duplicate]我对javascript嵌套承诺有一些问题[重复]
【发布时间】:2020-06-26 03:18:35
【问题描述】:

我是 js 新手,很难理解 Promise 和嵌套 Promise。为什么当我的承诺返回错误时,它仍然加载嵌套的.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 中执行我的代码。那么()?

【问题讨论】:

    标签: javascript ecmascript-6 es6-promise


    【解决方案1】:

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

    因此,在记录错误后,您需要再次抛出错误。

    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 一样工作。如果您捕捉到错误并且不重新抛出,则该异常被视为“已处理”并继续正常执行。 Promise 与它们的错误处理程序的工作方式相同。

    【讨论】:

    • 非常感谢。它解决了我的问题,现在对 Promise 有了更多的了解。
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2018-09-25
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多