核心点
promise在生命周期内有三种状态,分别是pending,fulfilled或rejected,状体改变只能是 pending-fulfilled,或者pending-rejected。并且状态一旦改变就不能再次改变。promise
题1函数
promise.resolve().then(() => { console.log('a'); return new Error('error'); }) .then((res)=>{ console.log('b'); console.log('then:',res); }) .catch((err) =>{ console.log('c'); console.log('catch:',err); })
可能有些同窗会认为出现了 new Error()就会想固然的认为会执行后面的catch函数,其实否则。code
在then函数中return了一个Error,依然会按照正常的流程走下去,并不会执行后续的catch函数,这个是不一样于thorw抛出一个Error的,若是是throw抛出一个Error则会被catch函数捕获。生命周期
因次答案是:io
a b c then:Error : error
题2console
const promise = Promise.resolve() .then(()=>{ return promise; }); promise.catch(console.error);
结果是function
TypeError:Chaining cycle detected for promise #<Promise>
咱们须要知道的是Promise的then或者catch里不能返回promise自己,不然会出现死循环,就是上面报的错误。循环
题3方法
Promise.resolve(1) .then(2) .then(Promise.resolve(3)) .then(console.log);
这个题目主要考察的是在 Promise的then或者catch方法中,接收的是一个函数,函数的参数是resolve或者rejiect函数的返回值,若是传入的值是非函数,那么就会产生值的穿透现象。
何为值穿透现象,简单理解就是传递的值会被直接忽略掉,继续执行链调用后续的方法。
因此 题3的 答案是 1.
第一个then接受值2 ,第二个接收一个Promise,都不是须要的函数,所以这二个then会发生值穿透。
而第三个then由于接收console.log函数,所以会执行,此时接收的是最开始的resolve(1)的值,所以最后返回 1.error
题4
Promise.resolve() .then(function success(res){ throw new Error('error'); },function faill(e){ console.error('fail1:',e); }) .catch(function fail2(e){ console.error('fail2',e); })
在Promise的then方法中,能够接收两个函数,一个是用于resolve成功的函数,一个是用于reject失败的函数,两个函数只会调用一个。咱们还能够经过.catch方法去实现then方法中的第二个表示失败的函数。
可是有一点不一样的是.catch方法能够捕获以前从then方法中抛出的Error,而then方法中的第二个方法捕获不到第一个处理成功的方法中抛出的Error。
所以咱们能够得出这道题目的答案,抛出fail2的Error。
上述的题目能够用下面的代码去理解
Promise.resolve() .then(function success1 (res){ thorw new Error('error'); },function() fail1(e){ console.error('fail1',e); }) .then(function success2(res){},function fail2(e){ console.error('fail2:',e); })