手写promise(不是分享,单纯记录 未完)

118 阅读1分钟
/**
 * // TODO: 1. resolvePromise: 返回promise, 或者return一个值,都要作为下一个promise的resolve。
 *          2. 第1个.then中报错,在要处理成第二个.then的resolve
 **/

class Promise {
    static PENDING = 'pending';
    static FULFILLED = 'fulfilled';
    static REJECTED = 'rejected';

    constructor(func) {
        this.PromiseState = Promise.PENDING
        this.PromiseResult = null
        this.onFulfilledCallbacks = [] // 
        this.onRejectedCallbacks = [] // 
        this.callback = (() => {
            try {
                return func(Promise.resolve.bind(this), Promise.reject.bind(this))
            } catch (e) {
                const reject = Promise.reject.bind(this)
                reject(e)
            }
        })()
    }

    static resolve(res) {
        if (this.PromiseState === Promise.PENDING) {
            this.PromiseState = Promise.FULFILLED
            this.PromiseResult = res
            setTimeout(() => {
                this.onFulfilledCallbacks.forEach(item => {
                    item(this.PromiseResult)
                })
            })
        }
    }

    static reject(err) {
        if (this.PromiseState === Promise.PENDING) {
            this.PromiseState = Promise.REJECTED
            this.PromiseResult = err
            setTimeout(() => {
                const onRejected = this.onRejectedCallbacks.forEach(item => {
                    item(this.PromiseResult)
                })
            })
        }

    }

    then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
        onRejected = typeof onRejected === 'function' ? onRejected : reason => {
            throw reason
        }
        if (this.PromiseState === Promise.PENDING) {
            this.onFulfilledCallbacks.push(onFulfilled) // 
            this.onRejectedCallbacks.push(onRejected) // 
        }

        if (this.PromiseState === Promise.FULFILLED) {
            setTimeout(() => {
                onFulfilled(this.PromiseResult)
            })

        }

        if (this.PromiseState === Promise.REJECTED) {
            setTimeout(() => {
                onRejected(this.PromiseResult)
            })
        }
        this.finally()
        return this
    }

    catch(onRejected) {
        if (this.PromiseState === Promise.REJECTED) {
            onRejected(this.PromiseResult)
        }
        this.finally()
        return this
    }

    finally(onFinally = () => { }) {
        if (this.PromiseState !== 'pending') onFinally()
    }
}
let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject("aaa")
    }, 1000);
})

let p2 = new Promise((resolve, reject) => {
    reject("bbb")
})

p1.then(
    res => {
        console.log('resolve了', res)
    },
    err => {
        console.log('reject了', err)
    }
)

p2.then(
    res => {
        console.log('resolve了', res)
    },
    err => {
        console.log('reject了', err)
    }
)

// TODO: