promise源码实现

class Promise {
	// 三状态:等待态、成功态、失败态
    static PENDING = 'pending'
    static RESOLVED = 'resolved'
    static REJECTED = 'rejected'
    constructor(excutor) {
    	// promise实例初始化
        this.state = Promise.PENDING // 默认为等待态
        this.value = undefined	// then方法成功回调函数的参数
        this.reason = undefined // then方法失败回调函数的参数
        this.resolveCallbacks = [] // 成功态回调队列
        this.rejectCallbacks = [] // 失败态回调队列
        // 定义成功态执行函数
        let resolve = (value) => {
        	// 只能从等待态改为成功态,状态改变后,不再改变
            if (this.state === Promise.PENDING) {
                this.state = Promise.RESOLVED
                this.value = value
                // 清空成功态回调队列
                this.resolveCallbacks.forEach(fn => fn())
            }
        }
        // 定义失败态执行函数
        let reject = (reason) => {
        	// 只能从等待态改为失败态,状态改变后,不再改变
            if (this.state === Promise.PENDING) {
                this.state = Promise.REJECTED
                this.reason = reason
                // 清空失败态回调队列
                this.rejectCallbacks.forEach(fn => fn())
            }
        }
        try {
        	// 执行构造函数回调
            excutor(resolve, reject)
        } catch (e) {
        	// 执行出错,则为失败态
            reject(e)
        }
    }
    then(onResolved, onRejected) {
    	// onResolved:成功态的回调函数
    	// onRejected:失败态的回调函数
    	// 如果onResolved和onRejected不是函数,那么就需要强制转换成函数
        onResolved = typeof onResolved === 'function' ? onResolved : val => val
        onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }
        //promise实例调用then方法都会返回一个新的promise实例
        return new Promise((resolve, reject) => {
            if (this.state === Promise.RESOLVED) {
            	// 成功态调用onResolved回调函数
            	// 用setTimeout模拟异步执行
                setTimeout(() => {
                    try {
                        const res = onResolved(this.value)
                        // 如果回调函数的返回值是一个promise实例,那么就执行该promise实例的then方法,并将resolve和reject作为该promise实例的成功回调和失败回调,递归执行直到该promise实例状态确定为止
                        if (res instanceof Promise) {
                            res.then(resolve, reject)
                        } else {
                        	//否则,就将这个值作为新的promise实例成功态的参数
                            resolve(res)
                        }
                    } catch (e) {
                    	// 回调函数执行出错,就将这个值作为新的promise实例失败态的参数
                        reject(e)
                    }
                });
            } else if (this.state === Promise.REJECTED) {
            	// 成功态调用onRejected回调函数
                setTimeout(() => {
                    try {
                        const res = onRejected(this.reason)
                        if (res instanceof Promise) {
                            res.then(resolve, reject)
                        } else {
                            resolve(res)
                        }
                    } catch (e) {
                        reject(e)
                    }
                });
            } else if (this.state === Promise.PENDING) {
            	// 如果当前是等待态,那么就将成功的回调和失败的回调分别加入成功回调队列和失败回调队列;
            	// 当状态改变为非等待态时,依次执行对应状态回调队列中的回调函数
                this.resolveCallbacks.push(() => {
                    try {
                        const res = onResolved(this.value)
                        if (res instanceof Promise) {
                            res.then(resolve, reject)
                        } else {
                            resolve(res)
                        }
                    } catch (e) {
                        reject(e)
                    }
                })
                this.rejectCallbacks.push(() => {
                    try {
                        const res = onRejected(this.reason)
                        if (res instanceof Promise) {
                            res.then(resolve, reject)
                        } else {
                            resolve(res)
                        }
                    } catch (e) {
                        reject(e)
                    }
                })
            }
        })
    }
    // 静态函数
    static resolve(promise) {
        return new Promise((resolve, reject) => {
            if (promise instanceof Promise) {
                promise.then(resolve, reject)
            } else {
                resolve(promise)
            }
        })
    }
    static reject(promise) {
        return new Promise((resolve, reject) => {
            reject(promise)
        })
    }
    static all(promises) {
        return new Promise((resolve, reject) => {
            let arr = []
            let cnt = 0

            function processData(index, value) {
                arr[index] = value
                if (++cnt === promises.length) {
                    resolve(arr)
                }
            }
            promises.forEach((p, index) => {
                Promise.resolve(p).then(res => {
                    processData(index, res)
                }, reject)
            })
        })
    }
    static race(promises) {
        return new Promise((resolve, reject) => {
            promises.forEach((p) => {
                Promise.resolve(p).then(resolve, reject)
            })
        })
    }
}
module.exports = Promise
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值