LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【JavaScript】新手如何手写Promise

admin
2024年12月25日 10:19 本文热度 839

一、Promise是个啥?

Promise是JavaScript中用于处理异步操作的对象,代表一个异步操作的最终完成(或失败)及其结果值。它有三种状态: pending (进行中)、 fulfilled (已成功)和 rejected (已失败)。状态一旦改变,就不会再变。

 

二、手写Promise基本结构

function MyPromise(executor) {
    // 初始状态为pending
    this.state = 'pending'; 
    // 成功的值
    this.value = undefined; 
    // 失败的原因
    this.reason = undefined; 


    // 存储成功回调函数
    const resolveCallbacks = []; 
    // 存储失败回调函数
    const rejectCallbacks = []; 


    // 定义resolve函数
    const resolve = (value) => {
        if (this.state === 'pending') {
            this.state = 'fulfilled';
            this.value = value;
            // 依次执行成功回调
            resolveCallbacks.forEach(callback => callback()); 
        }
    };


    // 定义reject函数
    const reject = (reason) => {
        if (this.state === 'pending') {
            this.state ='rejected';
            this.reason = reason;
            // 依次执行失败回调
            rejectCallbacks.forEach(callback => callback()); 
        }
    };


    try {
        executor(resolve, reject);
    } catch (error) {
        reject(error);
    }
}

 

三、实现then方法

 then 方法用于为Promise添加成功和失败回调。

MyPromise.prototype.then = function (onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function'? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function'? onRejected : reason => { throw reason };


    return new MyPromise((resolve, reject) => {
        if (this.state === 'fulfilled') {
            setTimeout(() => {
                try {
                    const x = onFulfilled(this.value);
                    resolvePromise(resolve, reject, x);
                } catch (error) {
                    reject(error);
                }
            });
        }


        if (this.state ==='rejected') {
            setTimeout(() => {
                try {
                    const x = onRejected(this.reason);
                    resolvePromise(resolve, reject, x);
                } catch (error) {
                    reject(error);
                }
            });
        }


        if (this.state === 'pending') {
            this.resolveCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        const x = onFulfilled(this.value);
                        resolvePromise(resolve, reject, x);
                    } catch (error) {
                        reject(error);
                    }
                });
            });


            this.rejectCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        const x = onRejected(this.reason);
                        resolvePromise(resolve, reject, x);
                    } catch (error) {
                        reject(error);
                    }
                });
            });
        }
    });
};

 

四、辅助函数resolvePromise

处理 then 回调返回值的逻辑。

function resolvePromise(resolve, reject, x) {
    if (x === resolvePromise) {
        return reject(new TypeError('Chaining cycle detected for promise'));
    }


    let called = false;


    if (x!== null && (typeof x === 'object' || typeof x === 'function')) {
        try {
            const then = x.then;
            if (typeof then === 'function') {
                then.call(x, y => {
                    if (called) return;
                    called = true;
                    resolvePromise(resolve, reject, y);
                }, r => {
                    if (called) return;
                    called = true;
                    reject(r);
                });
            } else {
                resolve(x);
            }
        } catch (error) {
            if (called) return;
            called = true;
            reject(error);
        }
    } else {
        resolve(x);
    }
}

 

五、测试MyPromise

const promise = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('Success!');
    }, 1000);
});


promise.then(value => {
    console.log(value); 
    return 'New value';
}).then(newValue => {
    console.log(newValue); 
});

OK 到这里一个简单的手写Promise就实现了,涵盖了Promise的基本状态管理、 then 方法及处理回调返回值的逻辑。


该文章在 2024/12/25 10:19:24 编辑过
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved