promise me,一定要学会手写一个Promise(七)

将函数的Promise改为class类型的

class Promise {
    constructor() {
        // 添加属性 
        this.PromiseState = 'pending';
        this.PromiseResult = null;
        this.callbacks = [];// 为了多个then链式调用,保存then方法中的参数
        //保存实例对象的this的值
        const self = this;

        function resolve(data) {
            //console.log(this);// window
            // 3. Promise的状态只能修改一次
            if (self.PromiseState !== 'pending') return
            // 1. 修改状态,promiseState
            self.PromiseState = 'resolved';//fullfilled
            // 2. 修改状态值,promiseResult
            self.PromiseResult = data;

            //调用成功的回调,即then函数的第一个参数
            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onResolved(data);
                });
            })
        }

        function reject(data) {
            // 3. Promise的状态只能修改一次
            if (self.PromiseState !== 'pending') return
            // 1. 修改状态,promiseState
            self.PromiseState = 'reject';//fullfilled
            // 2. 修改状态值,promiseResult
            self.PromiseResult = data;

            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onReject(data);
                });
            })

        }

        try {
            // 执行期的函数,在内部时同步调用的
            excutor(resolve, reject);
        } catch (e) {
            // 修改promise对象的状态和值
            reject(e);
        }
    }

    // then
    then(onResolved, onReject) {
        const self = this;// Promise
        // 判断回调函数参数-原生允许不穿onReject
        if (typeof onReject !== 'function') {
            onReject = reason => {
                throw reason;
            }
        }
        if (typeof onResolved !== 'function') {
            onResolved = value => value;
        }
        return new Promise((resolve, reject) => {
            // 封装函数
            function callback(type) {
                try {
                    let result = type(self.PromiseResult);
                    // 判断result
                    if (result instanceof Promise) {
                        result.then((value) => {
                            resolve(value);
                        }, (reason) => {
                            reject(reason);
                        })
                    } else {
                        // 结果的对象状态为成功
                        resolve(result);
                    }
                } catch (e) {
                    reject(e);
                }
            }
            // 当Promise状态为成功,调用此函数
            if (self.PromiseState === 'resolved') {
                setTimeout(() => {
                    callback(onResolved);
                })
            }
            // 当Promise状态为成功,调用此函数
            if (self.PromiseState === 'reject') {
                setTimeout(() => {
                    callback(onReject);
                })
            }

            // 当excutor的方法体为一个异步函数时,this.PromiseState 为pending
            if (this.PromiseState === 'pending') {
                this.callbacks.push({
                    onReject: function () {
                        callback(onReject);
                    },
                    onResolved: function () {
                        // 判断执行结果
                        callback(onResolved);
                    }
                })
            }
        })

    }
    // catch
    catch(onReject) {
        const self = this;
        return self.then(undefined, onReject);
    }

    // resolve 及以下为类方法,static
    static resolve(value) {
        return new Promise((resolve, reject) => {
            if (value instanceof Promise) {
                value.then(value => {
                    resolve(value);
                }, reason => {
                    reject(reason);
                })
            } else {
                // 状态为成功,值为value
                resolve(value);
            }
        });
    }

    static reject(value) {
        return new Promise((resolve, reject) => {
            if (value instanceof Promise) {
                value.then(value => {
                    resolve(value);
                }, reason => {
                    reject(reason);
                })
            } else {
                // 状态为失败,值为value
                reject(value);
            }
        });
    }

    static all(promises) {
        return new Promise((resolve, reject) => {
            let count = 0;
            let arr = [];
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(
                    v => {
                        // 得到promise的状态为成功
                        count++;
                        //将当前promise成功的结果存入数组中,顺序对应
                        arr[i] = v;
                        //判断promises里的每一个都为成功
                        if (count === promises.length) {
                            resolve(arr);
                        }
                    },
                    r => {
                        // 得到promise的状态为失败
                        reject(r);
                    })
            }
        });
    }

    static race(promises) {
        return new Promise((resolve, reject) => {
            let count = 0;
            let arr = [];
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(
                    v => {
                        resolve(arr);
                    },
                    r => {
                        // 得到promise的状态为失败
                        reject(r);
                    })
            }
        });
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴为您提供一个手写Promise 实现,代码如下: class Promise { constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onResolvedCallbacks.forEach((fn) => fn()); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach((fn) => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value; onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason }; const promise2 = new Promise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { const x = onFulfilled(this.value); Promise.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.state === 'rejected') { setTimeout(() => { try { const x = onRejected(this.reason); Promise.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.state === 'pending') { this.onResolvedCallbacks.push(() => { setTimeout(() => { try { const x = onFulfilled(this.value); Promise.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { const x = onRejected(this.reason); Promise.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); } }); return promise2; } static resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise')); } let called = false; if (x instanceof Promise) { x.then((value) => { Promise.resolvePromise(promise2, value, resolve, reject); }, reject); } else if (x !== null && (typeof x === 'object' || typeof x === 'function')) { try { const then = x.then; if (typeof then === 'function') { then.call(x, (value) => { if (called) return; called = true; Promise.resolvePromise(promise2, value, resolve, reject); }, (reason) => { if (called) return; called = true; reject(reason); }); } else { resolve(x); } } catch (error) { if (called) return; called = true; reject(error); } } else { resolve(x); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值