promise 源码实现

这篇博客详细介绍了如何使用JavaScript实现Promise的单例模式,通过立即执行函数封装,确保在不同场景下Promise的正确性和一致性。文章中展示了类MyPromise的构造及方法,包括状态管理、任务队列、then和catch方法的实现,并提供了静态方法如resolve、reject、all和race的实现,帮助理解Promise的工作原理。
摘要由CSDN通过智能技术生成

废话不多说直接上代码,这里用到了 单例模式和 立即执行函数思想

const MyPromise = (() => {
    // 定义三种状态
    const PENDING = "pending";
    const RESOLVED = "resolved";
    const REJECTED = "rejected";

    //定义不让外界访问的符号属性,状态和数据
    const PromiseResult = Symbol("PromiseResult")
    const PromiseState = Symbol("PromiseState")

    const changeStatus = Symbol("changeStatus")

    // 定义两个任务队列:成功的后续处理和失败后续处理
    const thenables = Symbol("thenables")
    const catchables = Symbol("catchables")

    const settleHandle = Symbol("settleHandle")

    return class MyPromise {
        /*
            newStatus 新的状态
            newValue 新的值
            queue 执行的任务队列
        */
        [changeStatus](newStatus, newValue, queue) {
            if (this[PromiseState] !== PENDING) {
                return
            }
            this[PromiseState] = newStatus;
            this[PromiseResult] = newValue;
            // console.log(queue)
            queue.forEach(element => {
                // console.log(element)
                return element(newValue)
            });
        }
        constructor(executor) {
            // 实例化对象的初始化
            this[PromiseState] = PENDING;
            this[PromiseResult] = undefined;

            // 定义任务队列的数组
            this[thenables] = []
            this[catchables] = []

            // 定义成功或失败的推向函数
            const resolve = data => {
                // if(this[PromiseState] !== PENDING){
                //     return
                // }
                // this[PromiseState] = RESOLVED;
                // this[PromiseResult] = data;
                this[changeStatus](RESOLVED, data, this[thenables])
            }
            const reject = reason => {
                // if(this[PromiseState] !== PENDING){
                //     return
                // }
                // this[PromiseState] = REJECTED;
                // this[PromiseResult] = reason;
                this[changeStatus](REJECTED, reason, this[catchables])
            }
            // executor(resolve,reject)
            try {
                executor(resolve, reject)
            } catch (error) {
                reject(error)
            }
        }
        then(thenable, catchable) {
            // if(this[PromiseState] === RESOLVED){
            //     thenable(this[PromiseResult])
            // }else{
            //     this[thenables].push(thenable)
            // }
            this[settleHandle](thenable, RESOLVED, this[thenables])
            this.catch(catchable)
        }
        catch (catchable) {
            // if(this[PromiseState] === REJECTED){
            //     catchable(this[PromiseResult])
            // }else{
            //     this[catchables].push(catchable)
            // }
            this[settleHandle](catchable, REJECTED, this[catchables])
        }
        // 提取公共代码
        /*
            handler 后续处理函数
            immediateStatus 立即执行的状态
            queue 任务队列
        */
        [settleHandle](handler, immediateStatus, queue) {
            if (this[PromiseState] === immediateStatus) {
                setTimeout(() => {
                    handler(this[PromiseResult])
                }, 0)
            } else {
                queue.push(handler)
            }
        }
        static resolve(data) {
            if (data instanceof MyPromise) {
                return data
            } else {
                return new MyPromise(res => {
                    res(data)
                })
            }
        }
        static reject(resaon) {
            return new MyPromise((res, rej) => {
                rej(resaon)
            })
        }
        static all(proms) {
            return new MyPromise((resolve, reject) => {
                const results = proms.map(p => {
                    const obj = {
                        res: undefined,
                        isResolved: false
                    }
                    p.then(data => {
                        obj.res = data;
                        obj.isResolved = true;
                        const unResolved = results.filter(r => !r.isResolved)
                        if (unResolved.length === 0) {
                            // 全部都是resolve
                            resolve(results.map(r => r.res))
                        }
                    }, reson => {
                        reject(reson)
                    })
                    return obj;
                })
            })
        }
        static race(proms) {
            return new MyPromise((resolve, reject) => {
                proms.forEach(p =>{
                    p.then(data=>{
                        console.log(11)
                        resolve(data)
                    },err=>{
                        console.log(22)
                        reject(err)
                    })
                })
            })
        }
    }
})()

如果有什么问题,欢迎回访

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值