We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
function fn1 () { try { fn2(); } catch (err) { console.log(err); // 不会打印 } } function fn2 () { setTimeout(function () { throw new Error('error'); // 只会抛出错误 }, 1000); }
当遇到返回的是promise(async 标识的函数就是返回promise),就无脑加async await。这样就可以try catch来捕捉异常。
async await
try catch
那么下面这个可以被捕捉到吗?
async function fn3 () { try { await fn4(); } catch (err) { console.log(err); // 不会打印 } } async function fn4 () { await setTimeout(function () { throw new Error('error'); // 只会抛出错误 }, 1000); }
不可以! await要加在异步的函数上面,返回回来才有意义。也就是setTimeout的回调函数。
await
setTimeout
需要这样使用:
async function fn5 () { try { await fn6(); } catch (err) { console.log(err); // 打印 error async } } function fn6 () { return new Promise((resolve, reject) => { setTimeout(function () { const r = Math.random(); if (r < 0.9) { reject('error async'); } }); }); }
正常情况,只有throw一个异常,才能被try catch到。但是await 具备promise里面reject出来的异常。可以理解成await又把reject给throw了,所以被catch到了。
throw
promise
reject
catch
The text was updated successfully, but these errors were encountered:
No branches or pull requests
try catch可能捕捉不到异步的异常
无脑方法
当遇到返回的是promise(async 标识的函数就是返回promise),就无脑加
async await
。这样就可以try catch
来捕捉异常。那么下面这个可以被捕捉到吗?
不可以!
await
要加在异步的函数上面,返回回来才有意义。也就是setTimeout
的回调函数。需要这样使用:
正常情况,只有
throw
一个异常,才能被try catch
到。但是await
具备promise
里面reject
出来的异常。可以理解成await
又把reject
给throw
了,所以被catch
到了。参考:纯正商业级应用-Node.js Koa2开发微信小程序服务端
The text was updated successfully, but these errors were encountered: