js简单手写实现下Prmoise

一、promise是什么

在JavaScript语言中,Promise是一种用于处理异步操作的对象,它代表了一个操作的最终完成(或失败)及其结果值。Promise提供了一种更加优雅和一致的方式来组织和管理异步代码,与传统的回调函数和回调地狱(callback hell)相比,Promise使得异步代码更易于阅读、理解和维护。

二、基本实现

核心思路点总结:

  • Promise三种状态的记录(pendding、resolved、rejected)和变更(通过resolve和reject函数变更)
  • 成功回调和失败回调函数的收集(在then中且pendding时候收集)
  • 成功回调和失败回调函数的触发(resolve和reject函数中触发)
  • then里自定义回调在什么时候触发(当状态变成resolved、rejected时候触发)

// 实现Promise

class MyPromise {
    PENDING = 'pendding';
    RESOLVED = 'resolved';
    REJECTED = 'rejected';

    constructor(fn) {
        this.status = this.PENDING;
        this.value = '';
        this.resolveCallbacks = [];
        this.rejectCallbacks = [];
        try {
            fn(this.resolve, this.reject);
        } catch (error) {
            this.reject(reject);
        }
    };
    resolve(value) {
        if (this.status === this.PENDING) {
            this.value = value;
            this.status = this.RESOLVED;
            this.resolveCallbacks.forEach(fn => fn(this.value));
        };
        return this;
    };
    reject(err) {
        if (this.status === this.PENDING) {
            this.value = err;
            this.status = this.REJECTED;
            this.rejectCallbacks.forEach(fn => fn(this.value));
        }
        return this;
    };
    then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : value => value;
        onRejected = typeof onRejected == 'function' ? onRejected : value => value;
        // 收集
        if (this.status === this.PENDING) {
            this.resolveCallbacks.push(onFulfilled);
            this.rejectCallbacks.push(onRejected);
        }
        // 触发后的处理
        if (this.status === this.RESOLVED) {
            onFulfilled(this.value);
        }
        if (this.status === this.REJECTED) {
            onRejected(this.value);
        }
        return this;
    };
    catch(onRejected) {
        onRejected = typeof onRejected == 'function' ? onRejected : value => value;
        if (this.status === this.PENDING) {
            this.rejectCallbacks.push(onRejected);
        }
        if (this.status === this.REJECTED) {
            onRejected(this.value);
        }
        return this;
    };
    finally(fn) {
        fn = typeof fn == 'function' ? fn : () => {};
        if (this.status === this.PENDING) {
            this.resolveCallbacks.push(fn);
            this.rejectCallbacks.push(fn);
        } else {
            fn();
        }
    };
}

三、Promise.race基本实现‘

核心思路点总结:

  • 异步执行每一个promise 只要其中一个执行完成那race就结束并拿到结果
  • 如果中途有promise出错直接Promise.all结束
Promise.prototype.race = function(promises) {
    return  new Promise((resolve, reject) => {
        for (let i = 0; i < promises.length; i ++) {
            let _promise = promises[i];
            if (_promise && _promise.then) {
                _promise.then(resolve, reject)
            } else {
                reject(_promise)
            }
        }
    })
}

四、 Promise.all基本实现

核心思路点总结:

  • 需要记录每一个promise的结果和顺序
  • 需要一个指针记录执行完成的promise数量
  • 当指针记录数等于promise数量时候结束Promise.all方法并返回结果
  • 如果中途有promise出错直接Promise.all结束
 Promise.prototype.all = function(promises) {
    let result = [];
    let point = 0;
    let proLen = promises.length;
    return new Promise((resolve, reject) => {
        for(let i = 0; i < proLen; i ++) {
            Promise.resolve(promises[i]).then(res => {
                result[i] = res;
                point++;
                if (point >= proLen) {
                    return resolve(result);
                }
            }, err => {
                return reject(err);
            })
        }
    })
 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LuckyCola2023

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

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

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

打赏作者

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

抵扣说明:

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

余额充值