手写一个简易 promise

首先要搞清promise的两个关键点:

  1. promise会返回一个状态(promiseState),且这个状态不可修改,只能在执行promise时修改一次
  2. promise会返回一个结果(promiseResult),这个结果储存了回调函数的返回值
// 构造函数
function Promise(executor) {
    const _this = this;
    _this.promiseState = 'pending'; // promise状态
    _this.promseResult = null; // promise结果
    _this.callbacks = []; // 回调函数then集合
    function resolve(data) {
        if(_this.promiseState !== 'pending') return;
        _this.promiseState = 'fulfilled';
        _this.promiseResult = data;
        // 这里添加setTimeout 是为了保证.then(v) 中的回调函数v异步
       setTimeout(() => {
           _this.callbacks.forEach(item => {
               item.onResolved(data);
           })
       })
    }
    function reject(data) {
        if(_this.promiseState !== 'pending') return;
        _this.promiseState = 'rejected';
        _this.pormiseResult = data;
        // 这里添加setTimeout 是为了保证.then(v,r) 中的回调函数r异步
        setTimeout(() => {
            _this.callbacks.forEach(item => {
                item.onRejected(data);
            })
        })
    }
    try {
        executor(resolve, reject);
    } catch(e) {
        reject(e);
    }
}

// 原型then方法
Promise.prototype.then = function(onResolved, onRejected) {
    const _this = this;
    if(typeof onResolved !== 'function') {
        onResolved = v => v;
    }
    if(typeof onRejected !== 'function') {
        onRejected = r => {
            throw r;
        }
    }
    return new Promise((resolve, reject) => {
        // 封装公共处理抛出异常函数
        function cb(type) {
            try {
                const result = type(_this.promiseResult);
                if(result instanceof Promise) {
                    result.then(v => {
                        resolve(v);
                    }, r => {
                        reject(r);
                    })
                } else {
                    resolve(result);
                }
            } catch(e) {
                reject(e);
            }
        }
        if(_this.promiseState === 'fulfilled') {
            // 这里添加setTimeout 是为了保证.then(v) 中的回调函数v异步
            setTimeout(() => {
                cb(onResolved);
            })
        }
        if(_this.promiseState === 'rejected') {
            // 这里添加setTimeout 是为了保证.then(v,r) 中的回调函数r异步
            setTimeout(() => {
                cb(onRejected);
            })
        }
        //判断 pending 状态
        if(_this.promiseState === 'pending') {
            _this.callbacks.push({
                onResolved: function() {
                    cb(onResolved);
                },
                onRejected: function() {
                    cb(onRejected);
                }
            })
        }
    })
}

// 原型catch方法
Promise.prototype.catch = function(onRejected) {
    return this.then(undefind, onRejected);
}

// 静态resolve方法
Promise.resolve(value) {
    return new Promise((resolve, reject) => {
        if(value instanceof Promise) {
            value.then(v => {
                resolve(value);
            },r => {
                reject(value);
            })
        } else {
            resolve(value);
        }
    })
}

// 静态reject方法
Promise.reject(reason) {
    return new Promise((resolve,reject) => {
        reject(reason);
    })
}

// 静态all方法  返回全部resolve的数组,或者返回第一个reject的结果
Promise.all(promises) {
    return new Promise((resolve, reject) => {
        let count = 0;
        let arr = [];
        for(let i = 0; i < promises.length; i++) {
            promises[i].then(v => {
                count++;
                // 此处使用数组下标保存是为了获得结果顺序与执行结果顺序一致
                arr[i] = v;
                if(count === promises.length) {
                    resolve(arr);
                }
            }, r => {
                reject(r);
            })
        }
    })
}

// 静态race方法 返回第一个最先的执行结果
Promise.race(promises) {
    return new Promise((resolve, reject) => {
        for(let i = 0; i < promises.length; i++) {
            promises[i].then(v => {
                resolve(v);
            }, r => {
                reject(r);
            })
        }
    })
}

使用class改造

class Promise{
    //构造方法
    constructor(executor){
        //添加属性
        this.PromiseState = 'pending';
        this.PromiseResult = null;
        //声明属性
        this.callbacks = [];
        //保存实例对象的 this 的值
        const self = this;// self _this that
        //resolve 函数
        function resolve(data){
            //判断状态
            if(self.PromiseState !== 'pending') return;
            //1. 修改对象的状态 (promiseState)
            self.PromiseState = 'fulfilled';// resolved
            //2. 设置对象结果值 (promiseResult)
            self.PromiseResult = data;
            //调用成功的回调函数
            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onResolved(data);
                });
            });
        }
        //reject 函数
        function reject(data){
            //判断状态
            if(self.PromiseState !== 'pending') return;
            //1. 修改对象的状态 (promiseState)
            self.PromiseState = 'rejected';// 
            //2. 设置对象结果值 (promiseResult)
            self.PromiseResult = data;
            //执行失败的回调
            setTimeout(() => {
                self.callbacks.forEach(item => {
                    item.onRejected(data);
                });
            });
        }
        try{
            //同步调用『执行器函数』
            executor(resolve, reject);
        }catch(e){
            //修改 promise 对象状态为『失败』
            reject(e);
        }
    }

    //then 方法封装
    then(onResolved,onRejected){
        const self = this;
        //判断回调函数参数
        if(typeof onRejected !== 'function'){
            onRejected = reason => {
                throw reason;
            }
        }
        if(typeof onResolved !== 'function'){
            onResolved = value => value;
            //value => { return value};
        }
        return new Promise((resolve, reject) => {
            //封装函数
            function callback(type){
                try{
                    //获取回调函数的执行结果
                    let result = type(self.PromiseResult);
                    //判断
                    if(result instanceof Promise){
                        //如果是 Promise 类型的对象
                        result.then(v => {
                            resolve(v);
                        }, r=>{
                            reject(r);
                        })
                    }else{
                        //结果的对象状态为『成功』
                        resolve(result);
                    }
                }catch(e){
                    reject(e);
                }
            }
            //调用回调函数  PromiseState
            if(this.PromiseState === 'fulfilled'){
                setTimeout(() => {
                    callback(onResolved);
                });
            }
            if(this.PromiseState === 'rejected'){
                setTimeout(() => {
                    callback(onRejected);
                });
            }
            //判断 pending 状态
            if(this.PromiseState === 'pending'){
                //保存回调函数
                this.callbacks.push({
                    onResolved: function(){
                        callback(onResolved);
                    },
                    onRejected: function(){
                        callback(onRejected);
                    }
                });
            }
        })
    }

    //catch 方法
    catch(onRejected){
        return this.then(undefined, onRejected);
    }

    //添加静态 resolve 方法
    static resolve(value){
        //返回promise对象
        return new Promise((resolve, reject) => {
            if(value instanceof Promise){
                value.then(v=>{
                    resolve(v);
                }, r=>{
                    reject(r);
                })
            }else{
                //状态设置为成功
                resolve(value);
            }
        });
    }

    //添加静态 reject 方法
    static reject(reason){
        return new Promise((resolve, reject)=>{
            reject(reason);
        });
    }

    //添加静态 all 方法
    static all(promises){
        //返回结果为promise对象
        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;
                    //判断
                    if(count === promises.length){
                        //修改状态
                        resolve(arr);
                    }
                }, r => {
                    reject(r);
                });
            }
        });
    }

    //添加静态 race 方法
    static race (promises){
        return new Promise((resolve, reject) => {
            for(let i=0;i<promises.length;i++){
                promises[i].then(v => {
                    //修改返回对象的状态为 『成功』
                    resolve(v);
                },r=>{
                    //修改返回对象的状态为 『失败』
                    reject(r);
                })
            }
        });
    }
}

你可能感兴趣的:(js篇,javascript,前端,开发语言)