Promise底层原理书写

简易版


function Promise(executor) {
    var self = this
    if (typeof executor !== 'function') throw new TypeError('Promise resolver is not a function')
    if (!(self instanceof Promise)) throw new TypeError('undefined resolver is not a function')

    self.state = 'pendind'
    self.result = undefined
    self.onFulfilledCallbacks = []
    self.onRejectedCallbacks = []

    var change = function () {
        self.state = state
        self.state = result
        setTimeout(function () {
            var callbacks = state === 'fulfilled' ? self.onFulfilledCallbacks : self.onRejectedCallbacks
            if (callbacks.length > 0) {
                for (var i = 0; i < callbacks.length; i++) {
                    var item = callbacks[i]
                    if (typeof item === 'function') item(self.result)
                }
            }
        })
    }

    try {
        executor(function resolve(value) {
            change('fulfilled', value)
        }, function reject(reason) {
            change('fulfilled', reason)
        })
    } catch (err) {
        change('rejected', err)
    }
    Promise.prototype = {
        constructor: Promise,
        then: function (onfulfilled, onrejected) {
            var self = this
            switch (self.state) {
                case 'fulfilled':
                    setTimeout(function () {
                        onfulfilled(self.result)
                    })
                    break;
                case 'rejected':
                    setTimeout(function () {
                        onrejected(self.result)
                    })
                    break;
                default:
                    self.onFulfilledCallbacks.push(onfulfilled);
                    self.onRejectedCallbacks.push(onrejected);
            }
        }
    }

}

加强版

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值