您为什么要尝试兑现承诺?那能抓住诺言的错误吗?

atk*_*yla 3 javascript promise ecmascript-6 es6-promise

我偶然发现了一些我不喜欢的代码:

try {
  somePromise()
    .then(res => console.log(res));
} catch (err) {
  console.error(err);
}
Run Code Online (Sandbox Code Playgroud)

如果某些操作somePromise()失败,将不会被捕获,并且应用程序将崩溃?这个try-catch甚至还能做什么?

应该是这样吗?:

  somePromise()
    .then(res => console.log(res))
    .catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

Kar*_*hik 7

TL; DR-如果返回诺言的函数在返回诺言之前引发异常,则必须在常规try-catch块中捕获该异常。

考虑这个功能

function asyncAdd(x,y){
   if(x === 2){
        throw new Error("good old exception")
   }else if(x === 1) { 
      return Promise.reject("fancy exception")
   }

   return Promise.resolve(x+y)
}
Run Code Online (Sandbox Code Playgroud)

这将打印“尝试捕获良好的旧异常”

try{
  asyncAdd(2,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
  console.error("Try caught", e);
}
Run Code Online (Sandbox Code Playgroud)

这将打印“ Promise catched fancy异常”

try{
  asyncAdd(1,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
  console.error("Try caught", e);
}
Run Code Online (Sandbox Code Playgroud)

  • 我可能会补充说,不应创建自己的既可以抛出也可以返回承诺的代码。尽管您可能必须防止这样做的他人代码,但是您不应允许自己的代码这样做,因为它会创建使安全使用感到痛苦的代码。 (3认同)