简体   繁体   English

异步函数内部的某些错误无法正常工作

[英]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. 我没有意识到classList.add('')是非法的。 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). 因此,当我在Firefox中运行代码时,它停止运行我的函数,但是没有出现错误,因为它是异步的(Chrome显示错误)。 This was hard to track down because in the original program the function with the classList.add was two function calls away. 这很难跟踪,因为在原始程序中,带有classList.add的函数被两个函数调用了。 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. 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() 

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. 这是因为从async块内部创建的promise的行为就像promise的行为一样—在发生任何错误的情况下,promise会被解析为rejected ,并将异常管道传递给您附加到拒绝路径的延续。

Two ways: 两种方式:

First - add explicit then to your promise: 首先-增加明确的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); } ); 

Second - make a try - catch block around await 第二- 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