美文网首页
2021-05-26 Promise

2021-05-26 Promise

作者: 半眼鱼 | 来源:发表于2021-05-26 10:36 被阅读0次
// 1、新建一个类。传入执行器

class MyPromise {
    constructor(executor) {
        executor()
    }
}

// 2、执行器传入resolve和reject方法

class MyPromise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }

    resolve = () => {}
    reject = () => {}
}

// 3状态和管理结果
const PENDING = 'Pending'
const FULFILLED = 'Fulfilled'
const REJECTED = 'Rejected'

class MyPromise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }

    status = PENDING;

    value = null; //成功
    reason = null; //失败

    resolve = (value) => {
        if (this.status = PENDING) {
            this.status = FULFILLED;
            this.value = value
        }
    }
    reject = (value) => {
        if (this.status = REJECTED) {
            this.status = REJECTED;
            this.value = value
        }
    }
}

// 4\then 实现



const PENDING = 'Pending'
const FULFILLED = 'Fulfilled'
const REJECTED = 'Rejected'

class MyPromise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }

    status = PENDING;

    value = null; //成功
    reason = null; //失败

    onFulFilledCallback = []
    onRejectCallback = []

    resolve = (value) => {
        if (this.status = PENDING) {
            this.status = FULFILLED;
            this.value = value

            // this.onFulFilledCallback && this.onFulFilledCallback(value)
            while (this.onFulFilledCallback.length) {
                this.onFulFilledCallback.shift()(value)
            }
        }
    }
    reject = (reason) => {
        if (this.status = REJECTED) {
            this.status = REJECTED;
            this.reason = reason
                // this.onFulFilledCallback && this.onFulFilledCallback(reason)
            while (this.onRejectCallback.length) {
                this.onRejectCallback.shift()(reason)
            }
        }
    }
    then(onFulfilled, onRejected) {
        const promise2 = new MyPromise((resolve, reject) => {
            if (this.status = FULFILLED) {
                const x = onFulfilled(this.value)
                resolvePromise(x, resolve, reject)
            } else if (this.status = REJECTED) {
                onRejected(this.value)
            } else if (this.status = PENDING) {
                this.onFulFilledCallback.push(onFulfilled)
                this.onRejectCallback.push(onRejected)
            }
        })

        return promise2
    }
}

function resolvePromise(x, resolve, reject) {
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}

// 5 暴露出去
module.exports = MyPromise

相关文章

网友评论

      本文标题:2021-05-26 Promise

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