在 Javascript 中等待函数时捕获错误的正确方法

Correct way to catch error when await for function in Javascript

我无法在我的函数中捕捉到拒绝。我在 google 搜索过,但我还没有找到解决方案,所以请帮我解决这段代码:

async function errorFunc(){
    setTimeout(() => {
        return Promise.reject("Any error occured!");
    }, 1000);
}
async function main(){
    await errorFunc().catch((error)=>{
        console.log("E in catch:", error);
    });
    
    try{
        await errorFunc();
    }catch(e){
        console.log("E in try-catch:", e);
    }
}

main();

没有一个捕获(在 main() 函数中)有效...在控制台中,只打印(两次)此错误消息:

Uncaught (in promise) Any error occured!

我想捕获那个错误(或者更好的说法是承诺拒绝)。我怎样才能在我的 main() 函数中做到这一点?

谢谢!

async function errorFunc(){
    return new Promise((resolve, reject) => setTimeout(() => reject("Any error occured!"), 1000))
}

这就是你想要的。


setTimeout(callback, ms)

callback 将在全局执行,没有人捕获它。

我认为它打印了两次相同的错误,因为在第二个函数中:

try{
        await errorFunc();
    }catch(e){
        console.log("E in try-catch:", error);
    }
}

你打印了“error”但捕获了“e”,我不太明白这个问题,但我想这就是它打印两次的原因,

也许将“error”与“e”交换以打印捕获到的另一个错误

您必须 return 来自函数的 Promise

async function errorFunc(){
   return new Promise((resolve,reject)=>{
   setTimeout(() => {
      return reject("Any error occured!");
   }, 1000);
  })
}

async function main(){
   await errorFunc().catch((error)=>{
      console.log("E in catch:", error);
   });

   try{
      await errorFunc();
   }catch(e){
      console.log("E in try-catch:", e);
   }
}