手写一个简单的Promise

2021-02-25  本文已影响0人  may505
function MayPromise(callback) {
    this.status = "pending"
    this.value = null
    this.successCallback = []
    const resolve = (value) => {
        if (this.status === "pending") {
            this.status = "success"
            this.value = value
            this.successCallback.map(item => item(value))
        }
    }
    const reject = value => {
        if (this.status === "pending") {
            this.status === "reject"
        }
    }
    callback(resolve, reject)
}

MayPromise.prototype.then = function (callback) {
    if (this.status === "success") {
        callback(this.value)
    } else if (this.status === "pending") {
        this.successCallback.push(callback)
    }
}
new MayPromise((resolve) => {
    setTimeout(() => {
        resolve('123456')
    }, 1000)
}).then(res => console.log('res', res))
上一篇下一篇

猜你喜欢

热点阅读