【JS】手写Promise基本功能

https://github.com/zjy4fun/notes/tree/main/demos/js-promise

三个状态,两个回调队列,then 的时候针对不同状态进行处理

const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class MyPromise {
    constructor(executor) {
        this.status = PENDING
        this.value = undefined
        this.reason = undefined
        this.onFulfilledCallbacks = []
        this.onRejectedCallbacks = []

        let resolve = (value) => {
            if (this.status === PENDING) {
                this.status = FULFILLED
                this.value = value
                this.onFulfilledCallbacks.forEach(fn => fn())
            }
        }

        let reject = (reason) => {
            if(this.status === PENDING) {
                this.status = REJECTED
                this.reason = reason
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }

        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }

    then(onFulfilled, onRejected) {
        if(this.state === FULFILLED) {
            onFulfilled(this.value)
        }

        if(this.state === REJECTED) {
            onRejected(this.reason)
        }

        if(this.state === PENDING) {
            this.onFulfilledCallbacks.push(() => {
                onFulfilled(this.value)
            })

            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }
    }
}

 

posted @ 2023-09-10 21:27  zjy4fun  阅读(3)  评论(0编辑  收藏  举报