比较这两个片段:
try {
console.log('start')
const test = (() => {
console.log('inside')
const a = null;
a.c = 1
})()
console.log('end')
} catch (error) {
console.log('nvmnghia');
console.error(error);
}
// prints:
// start
// inside
// nvmnghia
// TypeError: set props of null
try {
console.log('start')
const test = (async () => { // Note the async without await
console.log('inside')
const a = null;
a.c = 1
})()
console.log('end')
} catch (error) {
console.log('nvmnghia');
console.error(error);
}
// prints:
// start
// inside
// end
// undefined, due to normal return
// Uncaught (in promise) TypeError: ...
// and no nvmnghia, which means the error wasn't caught indeed
为什么会有这样的表现?我很惊讶,因为我对
async
/promise 的心智模型一直是第一个 await
之前的部分是同步运行的,即没有安排在微任务中。