【问题标题】:Can both a then() and catch() clause fire or is it just one or the other?then() 和 catch() 子句都可以触发还是只是其中之一?
【发布时间】:2019-05-21 19:09:14
【问题描述】:

是否存在then()catch() 都会触发的情况?

read(start).then(() => {
  console.log('DONE:', h.addCommas(data));
}).catch((err)=>{
  console.log('ERROR:');
  console.log(err);
})

【问题讨论】:

  • 如果 then 代码引发异常怎么办?
  • ^ 这就是原因。 (或者如果它返回一个被拒绝的承诺。)
  • 如果你想反应,无论叫什么,你都可以使用.finally()
  • then() 方法返回一个 Promise。它最多需要两个参数:Promise 成功和失败情况的回调函数。所以每当写在承诺中的代码引发异常时,catch() 方法就会触发,所以在这种情况下,两个方法都会调用

标签: javascript node.js promise


【解决方案1】:

是的,两者都可以开火。

案例 1doSomething().then(successHandler).catch(errorHandler) - 如果doSomething 成功并且successHandler 抛出,则errorHandler 将触发(否则不会触发)。

案例 2doSomething().catch(errorHandler).then(successHandler) - 如果 doSomething 抛出并且 errorHandler 没有抛出,则 successHandler 将触发(否则不会)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多