javascript promise 抛出错误时的陷阱

有些原因要弄懂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
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值