实现简单的promise

2019-12-08  本文已影响0人  sorry510
function MyPromise(executor) {
    this.value = null
    this.state = 'pending'
    this.resolveQueue = []
    this.rejectQueue = []

    var _this = this
    function resolve(value) {
        if(value instanceof MyPromise) {
            return value.then(resolve, reject)
        }
        setTimeout(function() {
            if(_this.state === 'pending') {
                _this.state = 'resolved'
                _this.value = value
                _this.resolveQueue.forEach(function(cb) { cb(value) })
            }
        }, 0)
    }
    function reject(value) {
        setTimeout(function() {
            if(_this.state === 'pending') {
                _this.state = 'rejected'
                _this.value = value
                _this.rejectQueue.forEach(function(cb) { cb(value) })
            }
        }, 0)
    }
    executor(resolve, reject)
}

MyPromise.prototype = {
    then(onFulfilled, onRejected) {
        if(this.state === 'pending') {
            this.resolveQueue.push(onFulfilled)
            this.rejectQueue.push(onRejected)
        }
        if(this.state === 'resolved') {
            onFulfilled(this.value)
        }
        if(this.state === 'rejected') {
            onRejected(this.value)
        }
        return this
    }
}

上一篇 下一篇

猜你喜欢

热点阅读