簡體   English   中英

異步函數內部的某些錯誤無法正常工作

[英]Some errors inside of async functions don't work properly

我在使用異步功能時遇到問題。 我沒有意識到classList.add('')是非法的。 因此,當我在Firefox中運行代碼時,它停止運行我的函數,但是沒有出現錯誤,因為它是異步的(Chrome顯示錯誤)。 這很難跟蹤,因為在原始程序中,帶有classList.add的函數被兩個函數調用了。 這是怎么回事,將來如何避免(除了必須在兩個不同的瀏覽器中檢查錯誤日志之外)? PS獎勵(如果您可以給出解釋的話),那么異步錯誤實際上不會停止執行的原因。

 async function error1(){ console.log('Fn async error: before') let a=undefined ab=1 console.log('after') } async function error2(){ console.log('Fn async noError: before') document.body.classList.add('') console.log('after') } function error3(){ console.log('Fn: before') document.body.classList.add('') console.log('after') } //Stops execution of function but not program //Throws an error in Chrome and Firefox error1() //Stops execution of function but not program //Throws an error in Chrome but not Firefox error2() //Errors and stops program error3() 

您應該等待執行,以便能夠捕獲可能的錯誤。 這是因為從async塊內部創建的promise的行為就像promise的行為一樣—在發生任何錯誤的情況下,promise會被解析為rejected ,並將異常管道傳遞給您附加到拒絕路徑的延續。

兩種方式:

首先-增加明確的then你的諾言:

  async function error1(){ console.log('Fn async error: before') let a=undefined ab=1 console.log('after') } error1().catch( e => { console.log( 'error: ' + e); } ); 

第二- try - catch await

 async function error1(){ console.log('Fn async error: before') let a=undefined ab=1 console.log('after') } (async function() { try { await error1(); } catch (e) { console.log( 'error: ' + e); } }()); 

暫無
暫無

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

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