实现自己的Promise

77 阅读1分钟
class NP {
    static PENDING = 'pending'
    static FULFILLED = 'fulfilled'
    static REJECTED = 'rejected'
    constructor(executor) {
        this.status = NP.PENDING
        this.callbacks = []
        this.nextCallBack = {}
        this.value = null
        executor(this.resolve.bind(this), this.reject.bind(this))
    }

    resolve(v) {
        if (this.status === NP.PENDING) {
            this.value = v
            this.status = NP.FULFILLED
            setTimeout(() => {
                this.callbacks.map(item => {
                    try {
                        let v = item.onFulFilled(this.value)
                        this.nextCallBack.resolve(v)
                    } catch (error) {
                        this.nextCallBack.reject(error)
                    }
                })
            });
        }
    }

    reject(v) {
        if (this.status === NP.PENDING) {
            this.value = v
            this.status = NP.REJECTED
            setTimeout(() => {
                this.callbacks.map(item => {
                    item.onRejected(this.value)
                })
            });
        }
    }

    then(onFulFilled = () => this.value, onRejected = () => this.value) {
        if (this.status === NP.PENDING) {
            this.callbacks.push({ onFulFilled, onRejected })
        }
        return new NP((resolve, reject) => {
            this.nextCallBack = { resolve, reject }
        })
    }
}