// 题目
try {
(async function () { a().b().c() })()
} catch (e) {
console.log(`执行出错:${e.message}`)
}
try {
setTimeout(function () {
console.log(b);
}, 0);
} catch (error) {
console.log('error', error); // 这里是不会执行的
}
console.log('out try catch')
// 异步,微任务
try {
new Promise(() => {
throw new Error('new promise throw error');
});
} catch (error) {
console.log('error', error);
}
// 这道题目主要三个考点:
// 执行一个没有定义的函数会发生什么
// 在 async 内部发生报错会发生什么
// try catch 只能捕获同步代码的异常
// 因此答案就明了了。
// 因为我们执行了一个未定义的函数,所以会报错 a is not defind,又因为是在 async 中,
// 所以报错信息会显示 in promise。最后 try cathch 只能捕获同步代码的抛错,
// 因为是 async,所以走不到 catch 里面。
// 如果我们把代码这样改一下就可以了:
try {
await (async function() { a().b().c() })()
} catch (e) {
console.log(`执行出错:${e.message}`)
}