javascript - 'catch' 在原生 Promise 链中是如何工作的?

标签 javascript google-chrome firefox promise

在 Chrome 或 Firefox 的控制台选项卡上尝试这段代码

var p = new Promise(function(resolve, reject) {
    setTimeout(function() {
        reject(10);
    }, 1000)
})

p.then(function(res) { console.log(1, 'succ', res) })
.catch(function(res) { console.log(1, 'err', res) })
.then(function(res) { console.log(2, 'succ', res) })
.catch(function(res) { console.log(2, 'err', res) })

结果会是

1 "err" 10
2 "res" undefined

我已经尝试了很多其他示例,但似乎第一个 then() 返回一个始终解决且从不拒绝的 promise 。我已经在 Chrome 46.0.2490.86 和 Firefox 42.0 上试过了。为什么会这样?我认为 then()catch() 可以链接多次?

最佳答案

就像在同步代码中一样:

try { 
    throw new Error();
} catch(e) {
    console.log("Caught");
}
console.log("This still runs");

异常处理之后运行的代码将运行 - 这是因为异常是一种错误恢复机制。通过添加该 catch,您表示错误已得到处理。在同步情况下,我们通过重新抛出来处理这个问题:

try { 
    throw new Error();
} catch(e) {
    console.log("Caught");
    throw e;
}
console.log("This will not run, still in error");

Promises 的工作方式类似:

 Promise.reject(Error()).catch(e => {
      console.log("This runs");
      throw e;
 }).catch(e => {
      console.log("This runs too");
      throw e;
 });

作为提示 - 永远不要拒绝非错误,因为你会丢失很多有用的东西,比如有意义的堆栈跟踪。

关于javascript - 'catch' 在原生 Promise 链中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34222818/

相关文章:

javascript - 从绑定(bind)到事件的另一个函数调用绑定(bind)到事件的函数不起作用

javascript - Base64:如何编码/解码页面的整个 HTML 代码

html - 为什么 Firefox 上的最小高度大于高度?

javascript - Chrome 扩展 : How to run a content_script after all the document's listeners are triggered?

javascript - 递归计算银行中的货币账户

Javascript 将一个表拆分为多个表

firefox - Greasemonkey 插件无法正常工作

android - 如何从 Android 应用程序打开特定浏览器

html - Bootstrap 导航栏不适用于 Chrome

html - 在 HTML 中设置新的预呈现或预取的正确方法是什么?