阮一峰的ECMAScript 6入门Promise对象第四小节提到:promise抛出一个错误,就被catch方法指定的回调函数捕获。
const promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error);
});
等同于:
// 写法一
const promise = new Promise(function(resolve, reject) {
try {
throw new Error('test');
} catch(e) {
reject(e);
}
});
promise.catch(function(error) {
console.log(error);
});
// 写法二
const promise = new Promise(function(resolve, reject) {
reject(new Error('test'));
});
promise.catch(function(error) {
console.log(error);
});
请问:为什么如下的形式,catch无法捕获错误
const promise = new Promise(function(resolve, reject) {
setTimeout(function () { throw new Error('test') }, 0)
});
promise.catch(function(error) { console.log(error) });
但如果改成如下两种形式就可以。
// 改写方法1
const promise = new Promise(function(resolve, reject) {
setTimeout(function () {
try{
throw new Error('test')
}catch(e){
reject(e)
}
}, 0)
});
// 改写方法2
const promise = new Promise(function(resolve, reject) {
setTimeout(function () {
reject(new Error('test'));
}, 0)
});
JS 事件循环列表有宏任务与微任务之分:setTimeOut是宏任务, promise是微任务,他们有各自的执行顺序;因此这段代码的执行是:
是因为你在setTimeOut主动触发了promise的reject方法,因此promise的catch将会在setTimeOut回调执行后的属于他的微任务队列中找到它然后执行,所以可以捕获错误