Promise 实现

  // promise手写
        /* 
            1.promise状态 pending(等待) resolve(成功) reject(失败)
            2. resolve 和 reject 函数 
            3. then方法的实现
            4.发布订阅者模式  实现异步
            5.链式调用  ( 返回  普通值 和 promise)
            6.resolve reject all race catch finally
         */
        const resolvePromise = (promise, x, resolve, reject) => {
            if (promise == x) {
                return reject(
                    new TypeError('Chaining cycle detected for promise #<promise>')
                )
            }
            if (typeof x == Object && x != null || typeof x == 'function') {
                let called //添加一个开放 state 只能改变一次
                try { // 获取then失败则直接rejecet(err)
                    let then = x.then
                    if (typeof then == 'function') {
                        then.call(x, res => {
                            // resolve(res) //采用promise的成功结果,并且向下传递
                            if (called) return
                            called = true
                            resolvePromise(promise, res, resolve, reject)
                        }, rej => {
                            if (called) return
                            called = true
                            reject(rej) //采用promise的失败结果,并且向下传递
                        })
                    } else {
                        if (called) return
                        called = true
                        resolve(x) //x不是一个函数是个对象
                    }
                } catch (err) {
                    if (called) return
                    called = true
                    reject(err)

                }
            } else {
                resolve(x) // x是一个普通的值
            }
        }

        class MyPromise {
            constructor(executor) {
                this.state = 'pedding' //状态
                this.value = undefined //成功返回的值
                this.reason = undefined //失败返回的值
                this.onResolvedCallbacks = [] //成功的回调队列
                this.onRejectCallbacks = [] // 失败的回调队列


                //成功的回调函数
                let resolve = (value) => {
                    if (this.state === 'pedding') {
                        this.state = 'resolved'
                        this.value = value
                        // 发布执行成功的函数
                        this.onResolvedCallbacks.forEach(fn => fn())
                    }
                }

                let reject = (reason) => {
                    if (this.state === 'pedding') {
                        this.state = 'rejected'
                        this.reason = reason
                        // 发布执行失败的函数
                        this.onRejectCallbacks.forEach(fn => fn())
                    }
                }
                try {
                    //执行new Promise(callback) 中的callback
                    executor(resolve, reject)
                } catch (err) {
                    // 失败直接返回失败的值
                    reject(err)
                }
            }
            resolve = (value) => {
                return new MyPromise((resolve, reject) => {
                    resolve(value)
                })
            }
            reject = (reason) => {
                return new MyPromise((resolve, reject) => {
                    reject(reason)
                })
            }

            // then方法的实现
            then(onResolved, onRejected) {
                // 递归实现链式调用
                let promise = new MyPromise((resolve, reject) => {
                    let x

                    // 状态为resolve,执行onResolved,传入成功的值
                    if (this.state == 'resolved') {
                        setTimeout(() => {
                            try {
                                x = onResolved(this.value)
                                // 添加一个resolvePromise()的方法来判断x跟promise的状态
                                //决定promise是走成功还是失败
                                resolvePromise(promise, x, resolve, reject)
                            } catch (err) { //中间任何一个环节报错都要走reject()
                                reject(err)
                            }
                        }, 0);
                    }
                    // 状态为rejected,执行onRejected,传入失败的值
                    if (this.state == 'rejected') {
                        setTimeout(() => {
                            try {
                                x = onRejected(this.reason)
                                resolvePromise(promise, x, resolve, reject)
                            } catch (err) {
                                reject(err)
                            }
                        }, 0);
                    }
                    // 异步 存储回调函数
                    if (this.status == 'pending') {
                        // 在pending状态 订阅成功失败的回调函数
                        this.onResolvedCallbacks.push(() => {
                            setTimeout(() => {
                                try {
                                    x = onResolved(this.value)
                                    resolvePromise(promise, x, resolve, reject)
                                } catch (err) {
                                    reject(err)
                                }
                            }, 0);
                        })
                        this.onRejectedCallbacks.push(() => {
                            setTimeout(() => {
                                try {
                                    x = onRejected(this.reason)
                                    resolvePromise(promise, x, resolve, reject)
                                } catch (err) {
                                    reject(err)
                                }
                            }, 0);
                        })
                    }

                })
                return promise
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值