console.log('here we go');new Promise( resolve => {
setTimeout( () => { console.log(2) throw new Error('bye');//这里不行
}, 2000); // throw new Error('bye');//放这里可以}).then( value => { console.log( value + ' world');
})
.catch( error => { console.log( 'Error:', error.message);
});
1 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
首先,在非async函数中,try-catch并不能捕获异步操作中产生的异常,Promise/setTimeout都是典型的异步操作。
其次,Promise的catch会在resolve被调用之前throw的Error对象,或者reject被调用后触发。
最后,setTimeout是个异步操作,当前操作执行完之后才会执行,所以当前的try-catch并不能处理setTimeout回调的异常。
综合以上3点,
你的
throw在setTimeout中,且没有reject,Promise不能catch到如果移动到
setTimeout下一句,相当于你的Promise没有resolve之前throw了Error
添加回答
举报
0/150
提交
取消
