手写promise

102 阅读1分钟

promise的出现是为了解决请求的嵌套调用的问题和合并多个任务请求结果

class myPromise
    {
        constructor (excutor) {
            this.status = 'pending'
            this.reason = ''
            this.value = ''    // 存放回调函数,原因excutor中可能存在异步操作,excutor执行完成后状态依然是pendding
            this.resolveCallBacks = []
            this.rejectCallBacks = []
            const resolve = (value) => {
                if (this.status === 'pending') {
                    this.status = 'fulfilled'
                    this.value = value
                    this.resolveCallBacks.map(fn => fn())
                }
            }
            const reject = (reason) => {
                if (this.status === 'pending') {
                    this.status = 'rejected'
                    this.reason = reason
                    this.rejectCallBacks.map(fn => fn())
                }
            }
            if (this.status === 'pending') {
                excutor(resolve, reject)
            }
        }
        then (onFulFilled, onRejected) {
            if (this.status === 'fulfilled') {
                onFulFilled(this.value)
            }
            if (this.status === 'rejected') {
                onRejected(this.reason)
            }
            if (this.status === 'pending') {
                this.resolveCallBacks.push(onFulFilled)
                this.rejectCallBacks.push(onRejected)
            }
        }
    }

需要注意的是:其中excutor其中存在异步操作, resolve和reject在异步操作中, 所以需要把回调函数存起来