手写Promise

class MyPromise {

    PENDING = 'pending'
    FULFILLED = 'fulfilled'
    REJECTED = 'rejected'

    status = null
    value = null
    resolveCallbacks = []
    rejectCallbacks = []

    constructor(executor) {
        this.status = this.PENDING
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
    }

    resolve(value) {
        if (this.status == this.PENDING) {
            this.status = this.FULFILLED
            this.value = value
            /**
             * 异步处理,回调
             */
            setTimeout(() => {
                this.resolveCallbacks.forEach((callback) => {
                    callback(this.value)
                })
            });
        }
    }

    static resolve(value) {
        return new MyPromise((resolve, reject) => {
            if (value instanceof MyPromise) {
                value.then(resolve, reject)
            } else {
                resolve(value)
            }
        })
    }

    reject(reason) {
        if (this.status == this.PENDING) {
            this.status = this.REJECTED
            this.value = reason
            /**
             * 异步处理,回调
             */
            setTimeout(() => {
                this.rejectCallbacks.forEach(callback => {
                    callback(this.value)
                })
            });
        }
    }

    static reject(reason) {
        return new MyPromise((resolve, reject) => {
            if (reason instanceof MyPromise) {
                reason.then(resolve, reject)
            } else {
                resolve(reason)
            }
        })
    }

    /**
     * then 方法应该异步执行,采用settimeout
     * @param {*} onFulfilled 
     * @param {*} onRejected 
     * @returns 
     */
    then(onFulfilled, onRejected) {
        // 实现不传的情况下穿透
        // 或者 if (onFulfilled === undefined && onRejected === undefined) return this
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => this.value
        onRejected = typeof onRejected === 'function' ? onRejected : () => this.value
        // 链式调用
        let promise2 = new MyPromise((resolve, reject) => {
            /**
             * 异步执行:
             * 1: 在做好的任务之后才能执行
             * 2: 需要加载链式后面的任务
             *

            /**
             * 异步任务的情况下,状态还未改变,需要保存回调,支持链式
             */
            if (this.status == this.PENDING) {
                this.resolveCallbacks.push(value => {
                    let result = onFulfilled(value)
                    if (result == promise2) throw TypeError("Chaining cycle detected")
                    // 如果返回的是一个promise 的处理
                    if (result instanceof MyPromise) {
                        result.then((value) => {
                            resolve(value)
                        }, reason => {
                            reject(reason)
                        })
                    } else {
                        resolve(result)
                    }

                })
                this.rejectCallbacks.push(value => {
                    let result = onRejected(value)
                    if (result == promise2) throw TypeError("Chaining cycle detected")
                    if (result instanceof MyPromise) {
                        result.then((value) => {
                            resolve(value)
                        }, reason => {
                            reject(reason)
                        })
                    } else {
                        resolve(result)
                    }

                })
            }

            if (this.status == this.FULFILLED) {
                setTimeout(() => {
                    let result = onFulfilled(this.value)
                    if (result == promise2) throw TypeError("Chaining cycle detected")
                    if (result instanceof MyPromise) {
                        result.then(value => {
                            resolve(value)
                        }, reason => {
                            reject(reason)
                        })
                    } else {
                        resolve(result)
                    }
                });
            }

            if (this.status == this.REJECTED) {
                setTimeout(() => {
                    let result = onRejected(this.value)
                    if (result == promise2) throw TypeError("Chaining cycle detected")
                    if (result instanceof MyPromise) {
                        result.then(value => {
                            resolve(value)
                        }, reason => {
                            reject(reason)
                        })
                    } else {
                        resolve(result)
                    }

                });

            }

        })
        return promise2
    }

    static all(promises) {
        const values = new Array(promises.length);
        return new MyPromise((resolve, reject) => {
            // 保证返回的数组是一致的
            promises.forEach((promise, index) => {
                promise.then((value) => {
                    values[index] = value
                    if (values.length == promises.length) resolve(values)
                }, (err) => {
                    reject(err)
                })

            })
        })
    }

    static race(promises) {
        return new MyPromise((resolve, reject) => {
            promises.forEach((promise) => {
                promise.then((data) => {
                    resolve(data)
                }, (err) => {
                    reject(err)
                })
            })
        })
    }

}

参考链接: https://www.bilibili.com/video/BV137411e7KA

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值