“捕获"在本地Promise链中如何工作? [英] How does the 'catch' work in a native Promise chain?

查看:53
本文介绍了“捕获"在本地Promise链中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome或Firefox的控制台标签上尝试这段代码

Try this piece of code on console tab of Chrome or 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()返回的诺言始终会解决,绝不会拒绝.我已经在Chrome 46.0.2490.86和Firefox 42.0上尝试过此操作.为什么会这样?我以为then()catch()可以链接多次?

I've tried many other examples but it seems that the first then() returns a promise that always resolves and never rejects. I've tried this on Chrome 46.0.2490.86 and Firefox 42.0. Why does this happen? I thought that then() and catch() can be chain multiple times?

推荐答案

就像在同步代码中一样:

Just like in the synchronous code:

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

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

Code that runs after the exception has been handled will run - this is because exceptions are an error recovery mechanism. By adding that catch you signaled that the error has been handled. In the synchronous case we handle this by rethrowing:

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

承诺的工作方式类似:

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

提示-不要丢掉非Error的东西,因为这样会丢失很多有用的东西,例如有意义的堆栈跟踪.

As a tip - never reject with non-Errors as you lose a lot of useful stuff like meaningful stack traces.

这篇关于“捕获"在本地Promise链中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆