Promise.then(a,b)和Promise.then(a).catch(b)一样吗?

and*_*ero 7 javascript promise es6-promise

有什么区别

因为这两种JavaScript表达式总是产生相同的结果,无论是内容和状态myPromise和功能的实现ab

除了代码可读性之外,我是否应该更喜欢使用一个而不是另一个?

amr*_*ngh 5

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

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);
});
Run Code Online (Sandbox Code Playgroud)

如果我们catch()在promise链的末尾只使用一个错误处理程序,就不会发生这种情况:请注意正如Bergi指出的那样,即使在多个catch()的情况下也会重现上述场景.

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));
Run Code Online (Sandbox Code Playgroud)

  • 你的例子毫无意义:即使你使用了两个`catch`块,下一个`then`回调也会被执行.这里的修复是删除一个错误处理程序,而不是使用不同的`then`语法.不,正如@ Ry-所说:通常*建议不要使用`catch` (2认同)

Mar*_*yer 3

它们在回调中处理错误的方式有所不同then(),在某些情况下,这可能是一个足够显着的差异,大多数人建议只使用catch().

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

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

使用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)
Run Code Online (Sandbox Code Playgroud)

除了一些测试场景之外,很难想到更喜欢这种行为的用例。

您可以同时使用两者,这将捕获回调中的拒绝和错误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))
Run Code Online (Sandbox Code Playgroud)

  • 实际上,只想处理某个承诺的拒绝是很常见的,这不仅仅是“一些测试场景”。 (2认同)