"捕获"如何在原生Promise链中发挥作用?

Kwi*_*wiZ 7 javascript firefox google-chrome 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) })
Run Code Online (Sandbox Code Playgroud)

结果将是

1 "err" 10
2 "res" undefined
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多其他的例子,但似乎第一个then()返回一个总是解决并且永不拒绝的承诺.我在Chrome 46.0.2490.86和Firefox 42.0上试过这个.为什么会这样?我认为then()catch()可链多次?

Ben*_*aum 8

就像在同步代码中一样:

try { 
    throw new Error();
} catch(e) {
    console.log("Caught");
}
console.log("This still runs");
Run Code Online (Sandbox Code Playgroud)

处理异常运行的代码将运行 - 这是因为异常是一种错误恢复机制.通过添加该捕获,您发出错误已被处理的信号.在同步的情况下,我们通过重新抛出来处理:

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

承诺的工作方式类似:

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

作为一个提示 - 永远不要拒绝非Errors,因为你失去了许多有用的东西,如有意义的堆栈跟踪.