小编Dea*_*hen的帖子

为什么promise 不能捕捉到setTimeout 抛出的错误?

为什么下面的代码无法捕获错误?“捕获”不起作用,错误抛出并退出。我在 nodeJs 8.9 上运行代码

new Promise(function(resolve,reject){
    console.log('construct a promise...')
    setTimeout(() => {
        throw new Error('async operation failure!')
    },1000)
})
.then(() => {
    //never happen
    console.log('happen?wrong!!!')
})
.catch(e => {
    console.warn('execute promise failure! catch it')
})
Run Code Online (Sandbox Code Playgroud)

如果删除 setTimeout,则“捕获”有效

new Promise(function(resolve,reject){
    console.log('construct a promise...')
    throw new Error('async operation failure!')
})
.then(() => {
    //never happen
    console.log('happen?wrong!!!')
})
.catch(e => {
    console.warn('execute promise failure! catch it')
})
Run Code Online (Sandbox Code Playgroud)

为什么会这样?请帮忙,谢谢!

javascript promise

2
推荐指数
2
解决办法
1738
查看次数

标签 统计

javascript ×1

promise ×1