手写Promise源码

Promise类核心逻辑

/*
1、Promise就是一个类,在执行这个类的时候,需要传递一个执行器进去,执行器就会立即执行
2、Promise中有三种状态,分别是成功fulfilled、失败rejected、等待pending
   pending->fulfilled
   pending->rejected
   一旦状态确定就不会改变
3、resolve和reject函数是用来更改状态的
   resolve:fulfilled
   reject:rejected
4、then方法内部做的事情就判断状态
   如果状态是成功,调用成功的回调函数
   如果状态是失败,调用失败的回调函数
   then方法是被定义在原型对象中的
5、then成功回调有一个参数,表示成功之后的值,then失败回调有一个参数,表示失败后的原因
*/

const PENDING = 'pending'
const FULFILLED = 'fulfiled'
const REJECTED = 'rejected'
class MyPromise{
    constructor(executor){
        executor(this.resolve,this.reject)
    }
    //Promise状态
    status = PENDING
    //成功之后的值
    value = undefined
    //失败后的原因
    reason = undefined
    resolve = value => {
        //如果状态不是等待,阻止程序向下执行
        if(this.status !== PENDING) return
        //将状态更改为成功
        this.status = FULFILLED
        //保存成功之后的值
        this.value = value
    }
    reject = reason => {
        //如果状态不是等待,阻止程序向下执行
        if(this.status !== PENDING) return
        //将状态更改为失败
        this.status = REJECTED
        //保存失败后的原因
        this.reason = reason
    }
    then(successCallback,failCallback){
        //判断状态
        if(this.status === FULFILLED){
            successCallback()
        }else if(this.status === REJECTED ){
            failCallback()
        }
    }
}

module.exports = MyPromise
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享