Promise.then(a,b)与Promise.then(a).catch(b)相同吗?

时间:2018-08-05 08:09:28

标签: javascript promise es6-promise

两者之间有什么区别

这两个JavaScript表达式是否总是产生相同的结果,而不管myPromise的内容和状态以及函数ab的实现如何?

除了代码可读性之外,还有什么情况比我更喜欢使用一种吗?

3 个答案:

答案 0 :(得分:5)

建议使用catch(),因为当我们在承诺链中使用myPromise.then(a, b)时,即使承诺被拒绝,next next next块也将始终执行。这是因为Promise链认为我们已经清除了错误处理程序中的错误。 看下面的例子: 即使我们reject()下一个next块也会执行。

function asyncFun(a,b){
  return new Promise((resolve, reject)=>{
      if(typeof a ==="number" && typeof b === "number")
        resolve(a + b);
      else
        reject("invalid data!!");
  });
}
asyncFun(2,'4').then((response)=>{
  console.log(response);
  return response;
}, (error)=>{
  console.log(error);
}).then((response)=>{
  console.log("console 2",response)
}, (error)=>{
  console.log(error);
});

如果在promise链的末尾仅使用单个错误处理程序catch(),则不会发生这种情况:请注意,正如Bergi指出的,即使发生多次捕获,也将重现上述情况( )。

function asyncFun(a,b){
  return new Promise((resolve, reject)=>{
      if(typeof a ==="number" && typeof b === "number")
        resolve(a + b);
      else
        reject("invalid data!!");
  });
}
asyncFun(2,'4').then((response)=>{
  console.log(response);
  return response;
}).then((response)=>{
  console.log("console 2",response)
}).catch((err)=> console.log(err));

答案 1 :(得分:2)

这些方法在处理then()回调中的错误的方式上有所不同,在某些情况下,它们之间的差异可能非常大,以致大多数人建议仅使用catch()

例如,使用catch(),您可以捕获此错误:

Promise.resolve('test')
.then(r => {
  throw("whoops")
})
.catch(e => console.log("caught error:", e))

无法使用then(a,b)样式:

Promise.resolve('test')
.then(r => { throw("whoops")},
      e => console.log("caught error?", e))
// unhandled rejection (you'll need to look in the console)

除了某些测试方案外,很难想到一个首选这种行为的用例。

您可以同时使用这两种方法,它们将在then()回调中捕获拒绝和错误,但这会使事情比您可能需要的混乱,除非您有特殊的用例来区分这两种错误。例如,哪个处理程序处理哪些错误:

Promise.reject("rejected")
.then(r => {throw("whoops")}, 
     e => console.log("Promise 1: caught error in second function:", e))
.catch(e=> console.log("Promise 1: caught error in catch", e))

Promise.resolve("rejected")
.then(r => {throw("whoops")}, 
     e => console.log("Promise 2: caught error in second function:", e))
.catch(e=> console.log("Promise 2: caught error in catch", e))

答案 2 :(得分:-1)

我认为这两种方法是相同的。但是,我更喜欢使用async().then().catch(),因为它更易于阅读。

此外,如果您想一个接一个地调用一些异步函数,但是如果抛出一些错误,则需要立即中断(不想继续运行以下函数)。您只需要在决赛中放入1个接球即可。在这种情况下,我们不能使用第一种样式。

asyncA()
    .then((val) => asyncB(val))
    .then((val) => asyncC(val))
    .then((val) => asyncD(val))
    .catch(() => { /* any of asyncA, asyncB, asyncC, asyncD will goes directly here if throwing error })
在上面的示例中

。您可以看到,任何异步功能均失败,该程序将跳过以下功能并直接捕获。

相关问题