4.多个Then处理

29 阅读1分钟
// 处理多个then
const PENDING = 'pending'
const FUFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    constructor (executor) {
        executor(this.resolve, this.reject)
    }
    status = PENDING
    value = undefined
    reason = undefined
    // 成功回调 改为 []
    successCallback = []
    // 失败回调 改为 []
    failCallback = []

    resolve = value => {
        if (this.status !== PENDING) return
        this.status = FUFILLED
        this.value = value
        // 如果成功回调存在,则执行等待中的成功回调 shift会逐个排出回调数组
        while(this.successCallback.length) this.successCallback.shift()(this.value)
    }
    reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        // 如果失败回调存在,则执行等待中的失败回调 shift会逐个排出回调数组
        while(this.failCallback.length) this.failCallback.shift()(this.reason)
    }
    then(successCallback, failCallback) {
        if (this.status === FUFILLED) {
            successCallback(this.value)
        } else if (this.status === REJECTED) {
            failCallback(this.reason)
        } else {
            // 表示进入了异步的等待状态
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    }
}

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

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

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

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