3AsyncPromise

21 阅读1分钟
// 基础promise实现上再处理异步情况处理
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 = undefined
    // 失败回调
    failCallback = undefined

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

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

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