簡體   English   中英

當我沒有在異步函數前面等待時,try catch塊會捕獲錯誤嗎?

[英]Will errors be caught by try catch block when I don't have await in front of my asynchronous function?

如果我沒有在異步函數之前等待,以下JavaScript try catch代碼塊是否仍會捕獲錯誤,如下所示?

async () => {
   try {
      someAsynchronouseFunction();
   } catch (err) {
      // will errors from my asynchronous function still be caught here?
   }
}

不,他們不會,因為someAsynchronouseFunction(); 只會解析為被拒絕的Promise ,而且僅被拒絕的Promise不會導致錯誤,即使在try塊中也不會導致錯誤。 取而代之的是,您只會看到Uncaught (in promise) Error: err! 在控制台中:

 async function someAsynchronouseFunction() { await new Promise(res => setTimeout(res, 1000)); console.log('end of someAsynchronouseFunction, about to throw'); throw new Error('err!'); } const foo = async () => { try { someAsynchronouseFunction(); } catch (err) { console.log('error found: ' + err); } console.log('end of foo'); } foo(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM