美文网首页
实现简单的promise

实现简单的promise

作者: sorry510 | 来源:发表于2019-12-08 18:35 被阅读0次
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
    }
}

相关文章

网友评论

      本文标题:实现简单的promise

      本文链接:https://www.haomeiwen.com/subject/eantmctx.html