【问题标题】:Does catch block not get executed if 'onRejected' function is provided for 'then' block in a Promise?如果 Promise 中的 'then' 块提供了 'onRejected' 函数,catch 块不会被执行吗?
【发布时间】:2021-07-17 14:07:57
【问题描述】:

这里是 Promise 的新手。

documentation(如下图所示)告诉它在内部调用 catch 块本身的 onRejected 函数。那么如果两个函数都提供了,那么在 Promise 中使用 catch 块有什么用处?

我尝试在 then 块中使用 throw 'error' 甚至 Promise.reject('error') 引发错误,但都没有触发 catch 块。

这是示例代码。

actionPromise = Promise.reject('error')  // or throw 'Error'
actionPromise
      .then(
        (response) => next({ ...rest, response, type: SUCCESS }),
        (error) => next({ ...rest, error, type: FAILURE })  // <--- Gets triggered
      )
      .catch((error) => {
        console.error('MIDDLEWARE ERROR:', error);  // <--- Not getting triggered
        next({ ...rest, error, type: FAILURE });
      });

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    如果 then 是,那么在 Promise 中有一个 catch 块有什么用 提供这两种功能?

    如果您向then() 方法提供promise 拒绝处理程序,那么只有当调用then() 方法的promise 被拒绝时,该处理程序才会执行。

    如果您从同一 then() 方法的实现处理程序中抛出错误,则也不会调用传递给 then() 方法的错误处理程序。

    下面的代码 sn -p 显示一个例子:

    Promise.resolve(123)
    .then(
      val => { throw val },
      error => console.log("inside error handler of first then")
    )
    .catch(error => console.log("inside catch method"));

    它与catch() 方法不同,因为catch() 方法将处理承诺链中任何在它之前的承诺的承诺拒绝。

    如果您抛出错误或返回被then() 方法的错误处理程序拒绝的promise,那么只有catch() 方法的回调函数才会被调用。

    下面的代码 sn -p 显示一个例子:

    Promise.reject(123)
    .then(
      val => console.log(val),
      error => { throw eror }
    )
    .catch(error => console.log("inside catch method")); 

    catch() 方法视为promise 链中所有前面promise 的全局错误处理程序,而then() 方法的错误处理程序在原始promise 上执行哪个then() 方法被调用,被拒绝。

    【讨论】:

    • 所以如果onResolvedonRejected 处理程序上没有发生错误的可能性,那么catch 块就没有用了吗?
    • 是的,没错。如果没有可能的未处理的 Promise 拒绝,那么您不需要 catch() 方法。话虽如此,使用catch() 方法比使用then() 方法的两个参数版本更常见,我建议使用catch() 方法,除非你真的需要使用then() 方法的两个参数版本.
    猜你喜欢
    • 2013-08-01
    • 2019-08-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多