使用class封装Promise

JS(ES6)实现Promise(resolve,reject,catch,then,all)

const isFunction = variable => typeof variable === 'function'
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class myPromise {
    constructor(handle) {
        if (!isFunction(handle)) {
            return new Error('参数必须为函数')
        }
        this._status = PENDING
        this._value = null
        this.fulfilledQueen = []
        this.rejectedQueen = []
        handle(this._resolve.bind(this), this._reject.bind(this))
    }
    // 添加resovle时执行的函数
    _resolve(val) {
        if (this._status !== PENDING) return
        this._status = FULFILLED
        this._value = val
    }
    // 添加reject时执行的函数
    _reject(err) {
        if (this._status !== PENDING) return
        this._status = REJECTED
        this._value = err
    }
    // then方法
    _then(onFulfilled, onReject) {
        let { _status, _value } = this
        switch (_status) {
            case PENDING:
                this.fulfilledQueen.push(onFulfilled)
                this.fulfilledQueen.push(onReject)
                break
            case FULFILLED:
                onFulfilled(_value)
                break
            case FULFILLED:
                onReject(_value)
                break
        }
        return new myPromise((onFulfillednext, onRejectnext) => { })
    }
    // catch方法
    _catch(onReject) {
        return this._then(undefined, onReject)
    }
    // all方法
    static _all(list) {
        return new myPromise((resolve, reject) => {
            let _value = []
            let num = 0
            for (let [i, p] of list.entries()) {
                this.resolve(p).then(res => {
                    _value[i] = res
                    num++
                    if (num === list.length) resolve(values)
                }, err => { reject(err) })
            }
        })
    }
}

在这里插入图片描述
太恶心了。。。。。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值