在上一篇文章中,我们对于promise有了初步的认识,我们了解到promise是new出来的对象,有三个对应pedding,fulfilled,rejected的状态,在初始化时,拥有status和value和初始化参数executor,executor需要传入resolve和reject函数作为参数。、
在本节我们继续来探索promise的原理,在了解基本的promse构造后,我们来对then方法进一步介绍,我们知道then是用来处理resolve和reject函数的回调。那么首先我们来定义then方法.
1、then方法需要两个参数,其中onFulfilled代表resolve成功的回调,onRejected代表reject失败的回调。
then(onFulfilled,onRejected){
}
2、我们知道promise的状态是不可逆的,在状态发生改变后,即不可再次更改,只有状态为FULFILLED才会调用onFulfilled,状态为REJECTED调用onRejected
then(onFulfilled,onRejected){
if(this.status == Promise.FULFILLED){
onFulfilled(this.value)
}
if(this.status == Promise.REJECTED){
onRejected(this.value)
}
}
3,then方法的每个方法都不是必须的,所以我们要处理当没有传递参数时,应该设置默认值
then(onFulfilled,onRejected){
if(typeof onFulfilled !=='function'){
onFulfilled = value => value;
}
if(typeof onRejected !=='function'){
onRejected = value => value;
}
if(this.status == Promise.FULFILLED){
onFulfilled(this.value)
}
if(this.status == Promise