为什么 Promise/async 函数的“同步”部分的错误处理方式不同

问题描述 投票:0回答:1

比较这两个片段:

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 之前的部分是同步运行的,即没有安排在微任务中。
    

javascript exception asynchronous
1个回答
0
投票

© www.soinside.com 2019 - 2024. All rights reserved.