【JS】手写Promise基本功能

发布时间 2023-09-10 21:34:38作者: zjy4fun

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

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

class MyPromise{
    constructor(executor) {
        this.state = 'pending' // fulfilled, rejected
        this.value = undefined
        this.reason = undefined

        // callbacks
        this.onFulfilledCallbacks = []
        this.onRejectedCallbacks = []

        // run
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch(error) {
            this.reject(error)
        }
    }

    resolve(value) {
        if(this.state === 'pending') {
            this.state = 'fulfilled'
            this.value = value

            // run all callbacks
            this.onFulfilledCallbacks.forEach(callback => callback(this.value))
        }
    }

    reject(reason) {
        if(this.state === 'pending') {
            this.state = 'rejected'
            this.reason = reason

            this.onRejectedCallbacks.forEach(callback => callback(this.reason))
        }
    }

    then(onFulfilled, onRejected) {
        if(this.state === 'fulfilled') {
            onFulfilled(this.value)
        } else if (this.state === 'rejected') {
            onRejected(this.reason)
        } else if (this.state === 'pending') {
            this.onFulfilledCallbacks.push(onFulfilled)
            this.onRejectedCallbacks.push(onRejected)
        }
        return this
    }
}