Promise

本文详细介绍了如何从头实现Promise,包括设置三种状态(PENDING、FULFILLED、REJECTED)、构造函数中的try-catch处理、初始化状态和方法如resolve、reject、then、catch和finally。通过实例展示了Promise链式调用的工作原理,以及静态方法如Promise.all和Promise.resolve的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

// 思路:
// 首先明确promise内需要填写的内容
// 1 先设置三个状态
// 2 构造函数里要写try catch 记录成功和失败
// 3 定义五个初始值 分别是status value reason successCallback failCallback
// 4 明确 普通方法--5个  静态方法--2个
// 分别是 resolve reject then finally catch
//        all resolve

//  3个状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    // 构造函数里用tye catch
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e);
        }
    }

    // 定义五个初始值
    status = PENDING;
    value = undefined;
    reason = undefined;
    successCallback = [];
    failCallback = [];

    resolve = value => {
        //判断状态是否是pending 如果是 那就return出去
        if (this.status !== PENDING) return;
        // 不是pending 那就成功 把状态修改并保存值
        this.status = FULFILLED;
        this.value = value;
        // 调用成功回调继续向下走
        // 先判断成功回调有没有
        this.successCallback && this.successCallback(this.value);
    }

    reject = reason => {
        //判断状态是否是pending 如果是 那就return出去
        if (this.status !== PENDING) return;
        // 不是pending 那就失败 把状态修改并保存原因
        this.status = REJECTED;
        this.reason = reason;
        // 调用失败回调
        // 先判断失败回调有没有
        this.failCallback && this.failCallback(this.reason);
    }
    // then中有两个参数 分别是成功回调和失败回调
    then(successCallback, failCallback) {
        // 成功 拿上一步给下来的值
        successCallback = successCallback ? successCallback : value => value;
        // 失败 记录失败原因
        failCallback = failCallback ? failCallback : reason => { throw reason };
        let promsie2 = new MyPromise((resolve, reject) => {
            // 判断status状态
            // 成功
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value);
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
                // 失败
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason);
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
                // pendding状态 此时将两种回调都储存起来 等待结果
            } else {
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
            }
        });
        return promsie2;
    }
    // 取到最后的值 同样也有成功和失败两种
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    // 捕获失败
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    // 将所有的都执行完
    static all(array) {
        let result = [];
        // 定义一个index 每执行一次就++
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                // 看index的值和数组的长度是否相等 如果相等了 那就是执行完毕了
                if (index === array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                // 用instanceof判断这个值是promise对象还是普通值
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, array[i]);
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值