有些原因要弄懂promise的源码才能明白
// Throwing an error will call the catch method most of the time
var p1 = new Promise(function(resolve, reject) {
throw new Error('Uh-oh!');
});
p1.catch(function(e) {
console.error(e); // "Uh-oh!"
});
// Errors thrown inside asynchronous functions will act like uncaught errors
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
//在源码里面,我们是try{executor()}catch(e){reject(e)};
//但是try catch是捕获不到setTimemout里面抛出的错误的,除非try catch写在setTimeout里面,所以promise的状态不会改变,promise的catch方法也不会起作用
throw new Error('Uncaught Exception!');
// return一个拒绝状态的promise就更没办法改变promise的状态了。本质原因就是try...catch...
// 无法捕获异步错误
// returning a rejected Promise is similar with throwing an Error
// return Promise.reject('Uncaught Exception')
// However, using 'reject' will trigger p2.catch callback;
// 这里的reject直接改变了promise的状态,然后catch方法的回调已经被保存到promise当中了,当这里状态改变时,就会直接把那些回调再拿出来执行
// reject('Uncaught Exception');
}, 1000);
});
p2.catch(function(e) {
console.error(e); // This is never called except reject('Uncaught Exception');
});
// Errors thrown after resolve is called will be silenced
var p3 = new Promise(function(resolve, reject) {
//Promise的状态只能由PENDING转换为FULFILLED或者REJECTED,在调用了resolve之后,promise的状态就已经变为FULFILLED了,
//所以后面在executor里面即使抛出的错误被try catch捕获到再调用了reject()方法,
//由于不满足当前状态为PENDING,reject方法中的if(this.status===PENDING)的判断也进不去
//当前的promise的状态也无法改变,所以catch方法也不会执行
resolve();
throw new Error('Silenced Exception!');
});
p3.catch(function(e) {
console.error(e); // This is never called
});