5.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
        while(this.successCallback.length) this.successCallback.shift()(this.value)
    }
    reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        while(this.failCallback.length) this.failCallback.shift()(this.reason)
    }
    then(successCallback, failCallback) {
        // 需要返回一个MyPromise类
        const promise2 = new MyPromise((resolve) => {
            if (this.status === FUFILLED) {
                // 将成功回调中返回的值传递下去
                const successValue = successCallback(this.value)
                // 将成功的值传递给下一个then并执行成功回调
                resolve(successValue)
            } else if (this.status === REJECTED) {
                failCallback(this.reason)
            } else {
                this.successCallback.push(successCallback)
                this.failCallback.push(failCallback)
            }
        })
        return promise2
    }
}

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

mypromise.then(values => {
    console.log(values)
    return 100
}).then(values => {
    console.log(values)
    return 200
}).then(values => {
    console.log(values)
})