手写promise类,简易版

83 阅读1分钟

Promise协议:

  1. promise的三种状态:pending、fulfilled、rejected
  2. promise状态的流转:pending->fulfilled 或 pending->rejected,且状态一旦改变就不会再次改变
  3. new Promise 执行器executor(resolve,reject)。
  4. promise,value保存成功状态的枚举:undefined/thenable/promise
  5. promise,保存失败状态值:reason
  6. promise一定会有then,then有两个回调函数:onFulfilled(value) + onRejected(reason)

类的调用方式:

const promise = new Promise((resolve, reject) => {
    setTimeout(()=>{
        resolve('成功')
    },1000)
}).then(data => {
    console.log(data,'kkk')
    console.log('kkkk')
})

类的实现:

// 三个状态:PENDING FULFILLED REJECTED
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

class Promise { // 类
    constructor(executor) { // 构造
        // 默认状态的处理: PENDING
        this.status = PENDING
        // 成功状态的值
        this.value = undefined
        // 失败状态的值
        this.reason = undefined
        // 存放成功的回调
        this.onResolvedCallbacks = []
        // 存放失败的回调
        this.onRejectedCallbacks = []
        // 成功状态的回调
        let resolve = value => {
            if (this.status === PENDING) {
                this.status = FULFILLED
                this.value = value
                // 依次调用对应函数的执行
                let callbacksArr = (this.onResolvedCallbacks || [])
                callbacksArr.forEach(fn => fn())
            }
        }
        // 失败状态的回调
        let reject = reason => {
            if (this.status === PENDING) {
                this.status = REJECTED
                this.reason = reason
                // 依次调用对应函数的执行
                (this.onRejectedCallbacks || []).forEach(fn => fn())
            }
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }

    then(onFulfilled, onRejected) {
        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        }
        if (this.status === REJECTED) {
            onRejected(this.reason)
        }
        if (this.status === PENDING) {
            this.onResolvedCallbacks.push(() => {
                onFulfilled(this.value)
            })
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }
    }
}