[英]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.