2MyPromise

18 阅读1分钟
// 基础版本Promise实现
const PENDING = 'pending'
const FUFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    constructor (executor) {
        // 执行器 executor
        executor(this.resolve, this.reject)
    }
    status = PENDING
    // 成功后的值
    value = undefined
    // 失败后的原因
    reason = undefined

    resolve = value => { // 这里写成尖头函数方便调用的时候 防止this指向全局
        // 状态不可逆
        if (this.status !== PENDING) return
        this.status = FUFILLED
        // 保存成功之后的值
        this.value = value
    }
    reject = reason => {
        // 状态不可逆
        if (this.status !== PENDING) return
        this.status = REJECTED
        // 保存失败之后的原因
        this.reason = reason
    }
    then(successCallback, failCallback) {
        if (this.status === FUFILLED) {
            // 返回成功之后的值
            successCallback(this.value)
        } else if (this.status === REJECTED) {
            // 返回失败之后的原因
            failCallback(this.reason)
        }
    }
}

// 验证
const mypromise =  new MyPromise((resolve, reject) => {
    resolve('successValue')
    // reject('failReason')
})

mypromise.then(value => {
    console.log(value)
}, reason => {
    console.log(reason)
})