rejected promise in try-catch

332 阅读1分钟

示例

demo1 & demo2 唯一的区别就是 demo2 加了 await,结果是 demo1 的错误没有被 catch,demo2 的错误被 catch 了。

// demo1
try {
    new Promise((resolve, reject) => {
        resolve()
    }).then(() => { throw new Error('haha') }) // Promise: {status: "rejected", value: Error: haha }
    console.log('irene test')
} catch(err) {
    console.log('irene')
}

打印结果

// demo2
try {
    await new Promise((resolve, reject) => { // 相比 demo1 加了 await
        resolve()
    }).then(() => { throw new Error('haha') })
    console.log('irene test')
} catch(err) {
    console.log('irene')
}

打印结果:irene

原因是:在 demo1 中,try-catch 先执行,try 中执行了

resolve();
console.log('irene test');

此时没有抛错,所以不会执行到 catch 中去,至此 try-catch block 已经结束。然后执行 promise.then callback,抛出了 Error ,由于 try-catch scope 已经没有了,所以不会被 catch住,在控制台报了这个错。在 demo2 中,由于使用了 await,它会等 promise.then callback 执行完,也就是在 try 中执行了

resolve();
throw new Error('haha');
console.log('irene test'); // 上面抛了错,所以 'irene test' 不会打印

此时抛出了 Error,所以会被 catch 住,控制台也就不会打印错误了。

类似的例子还有如下,结合事件循环的思路会更容易理解:

try {
  setTimeout(() => {
    throw new Error('haha')
  })
  console.log('irene test')
} catch(e) { // Error: haha 不会在此处被 catch
  console.log(e)
}

stackoverflow.com/questions/6…

错误处理机制