手写promise

// 可以实现异步的promise
class myPromise {
    constructor(fn) {
        this.state = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // 成功存放的数组
        this.onResolvedCallbacks = [];
        // 失败存放法数组
        this.onRejectedCallbacks = [];
        let resolve = function(value) {
            if (this.state === 'pending') {
                this.state == 'fulfilled';
                this.value = value;
                // 一旦resolve执行,调用成功数组的函数
                this.onResolvedCallbacks.forEach(fn => fn());
            }
        };
        let reject = function(reason) {
            if (this.state === 'pending') {
                this.state = 'rejected';
                this.reason = reason;
                // 一旦reject执行,调用失败数组的函数
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        };
        try {
            fn(resolve, reject)
        } catch (e) {
            reject(e)
        }
    };
    then(onFulfilled, onRejected) {
        // 状态为fulfilled,执行onFulfilled,传入成功的值
        if (this.state === 'fulfilled') {
            onFulfilled(this.value);
        };
        // 状态为rejected,执行onRejected,传入失败的原因
        if (this.state === 'rejected') {
            onRejected(this.reason);
        };
        // 当状态state为pending时
        if (this.state === 'pending') {
            // onFulfilled传入到成功数组
            this.onResolvedCallbacks.push(() => {
                    onFulfilled(this.value);
                })
                // onRejected传入到失败数组
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason);
            })
        };
    };
    catch (fn) {
        return this.then(null, fn);
    }
};
// 实现链式的promise.then
function then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
    let promise2 = new Promise((resolve, reject) => {
        if (this.state === 'fulfilled') {
            setTimeout(() => {
                try {
                    let x = onFulfilled(this.value);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e);
                }
            }, 0);
        };
        if (this.state === 'rejected') {
            setTimeout(() => {
                try {
                    let x = onRejected(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e);
                }
            }, 0);
        };
        if (this.state === 'pending') {
            this.onResolvedCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        let x = onFulfilled(this.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            });
            this.onRejectedCallbacks.push(() => {
                setTimeout(() => {
                    try {
                        let x = onRejected(this.reason);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
            });
        };
    });
    return promise2;
};

// promiseALL方法
// 返回结果是数组,顺序和传参顺序一样
function promiseAll(promises) {
    if (!Array.isArray(promises)) {
        throw new Error('不是数组')
    };
    return new Promise(function(resolve, reject) {
        let count = 0;
        let arr = [];
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(
                function(value) {
                    arr[i] = value;
                    count++;
                    if (count === len) {
                        return resolve(arr)
                    }
                },
                function(reason) {
                    return reject(reason)
                })
        }
    })
}
// promiseRace方法
// 只返回最快的结果
function promiseRace(promises) {
    if (!Array.isArray(promises)) {
        throw new Error('不是数组')
    };
    return new Promise(function(resolve, reject) {
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(
                function(value) {
                    return resolve(value)
                },
                function(reason) {
                    return reject(reason)
                })
        }
    })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天都在掉头发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值