简体   繁体   中英

Some errors inside of async functions don't work properly

I ran into a problem in using async functions. I didn't realize that classList.add('') is illegal. So, when I was running my code in Firefox it stopped running my function, but no error appeared because it was async (Chrome shows the error). This was hard to track down because in the original program the function with the classList.add was two function calls away. What is going here and how do I avoid it in the future (besides having to check the error logs in two different browsers)? PS bonus if you can give explain the reason why async errors don't actually halt execution.

 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() 

You should await the execution which makes it possible to catch possible errors. This is because the promise that is created internally from your async block behaves as a promise should behave - in case of any errors, the promise resolves as rejected and passes the exception the pipeline to the continuation you attach to the rejecting path.

Two ways:

First - add explicit then to your promise:

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

Second - make a try - catch block around 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); } }()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM