promise A+规范es6实现

6 篇文章 0 订阅

参考文章:https://www.jianshu.com/p/459a856c476f

/**
 * Promise 实现 遵循promise/A+规范
 * Promise/A+规范译文:
 * https://malcolmyu.github.io/2015/06/12/Promises-A-Plus/#note-4
 * 中文译文
 * https://www.icode9.com/content-4-365156.html
 */

// promise的状态枚举
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class Promise {
    constructor(executor) {
        this.status = PENDING;
        this.value = undefined;         // 初始状态
        this.reason = undefined;        // fulfilled状态时 返回的信息
        this.onFulfilledCallbacks = []; // 存储fulfilled状态对应的onFulfilled函数
        this.onRejectedCallbacks = [];  // 存储rejected状态对应的onRejected函数

        this.resolve = (value) => {     // value成功态时接收的终值
            if (value instanceof Promise) {
                return value.then(this.resolve, this.reject);
            }

            // 为什么resolve 加setTimeout?
            // 2.2.4规范 onFulfilled 和 onRejected 只允许在 execution context 栈仅包含平台代码时运行.
            // 注1 这里的平台代码指的是引擎、环境以及 promise 的实施代码。实践中要确保 onFulfilled 和 onRejected
            // 方法异步执行,且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。

            setTimeout(() => {
                // 调用resolve 回调对应onFulfilled函数
                if (this.status === PENDING) {
                    // 只能由pedning状态 => fulfilled状态 (避免调用多次resolve reject)
                    this.status = FULFILLED;
                    this.value = value;
                    this.onFulfilledCallbacks.forEach(fn => {
                        fn(this.value);
                    })

                }
            })
        }

        this.reject = (reason) => {    // reason失败态时接收的拒因
            setTimeout(() => {
                // 调用reject 回调对应onRejected函数
                if (this.status === PENDING) {
                    // 只能由pedning状态 => rejected状态 (避免调用多次resolve reject)
                    this.status = REJECTED;
                    this.reason = reason;
                    this.onRejectedCallbacks.forEach(fn => {
                        fn(this.reason);
                    })
                }
            })

        }


        /**
         * resolve中的值几种情况:
         * 1.普通值
         * 2.promise对象
         * 3.thenable对象/函数
         */

        /**
         * 对resolve 进行改造增强 针对resolve中不同值情况 进行处理
         * @param  {promise} promise2 promise1.then方法返回的新的promise对象
         * @param  {[type]} x         promise1中onFulfilled的返回值
         * @param  {[type]} resolve   promise2的resolve方法
         * @param  {[type]} reject    promise2的reject方法
         */
        this.resolvePromise = (promise2, x, resolve, reject) => {
            if (promise2 === x) { // 如果从onFulfilled中返回的x 就是promise2 就会导致循环引用报错
                return reject(new TypeError('循环引用'));
            }
            let called = false;   // 避免多次调用
            // 如果 x 为对象或者函数
            if (x !== null && ((typeof x === 'object') || (typeof x === 'function'))) {
                try { // 是否是thenable对象(具有then方法的对象/函数)
                    let then = x.then;
                    if (typeof then === 'function') {
                        then.call(x, y => {
                            if (called) return;
                            called = true;
                            this.resolvePromise(promise2, y, resolve, reject);
                        }, reason => {
                            if (called) return;
                            called = true;
                            reject(reason);
                        })
                    } else {
                        resolve(x);
                    }
                } catch (e) {
                    if (called) return;
                    called = true;
                    reject(e);
                }
            } else {
                resolve(x);
            }

        }

        // 捕获在excutor执行器中抛出的异常
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch (err) {
            this.reject(err)
        }

    }

    /**
     * [注册fulfilled状态/rejected状态对应的回调函数]
     * @param  {function} onFulfilled fulfilled状态时 执行的函数
     * @param  {function} onRejected  rejected状态时 执行的函数
     * @return {function} newPromsie  返回一个新的promise对象
     */
    then(onFulfilled, onRejected) {
        let newPromise;
        // 处理参数默认值 保证参数后续能够继续执行
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
        onRejected = typeof onRejected === 'function' ? onRejected : reason => {
            throw reason;
        };
        // then里面的FULFILLED/REJECTED状态时 为什么要加setTimeout ?
        // 原因:
        // 其一 2.2.4规范 要确保 onFulfilled 和 onRejected 方法异步执行(且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行) 所以要在resolve里加上setTimeout
        // 其二 2.2.6规范 对于一个promise,它的then方法可以调用多次.(当在其他程序中多次调用同一个promise的then时
        // 由于之前状态已经为FULFILLED/REJECTED状态,则会走的下面逻辑),所以要确保为FULFILLED/REJECTED状态后 也要异步执行onFulfilled/onRejected

        // 其二 2.2.6规范 也是resolve函数里加setTimeout的原因
        // 总之都是 让then方法异步执行 也就是确保onFulfilled/onRejected异步执行

        // 如下面这种情景 多次调用p1.then
        // p1.then((value) => { // 此时p1.status 由pedding状态 => fulfilled状态
        //     console.log(value); // resolve
        //     // console.log(p1.status); // fulfilled
        //     p1.then(value => { // 再次p1.then 这时已经为fulfilled状态 走的是fulfilled状态判断里的逻辑 所以我们也要确保判断里面onFuilled异步执行
        //         console.log(value); // 'resolve'
        //     });
        //     console.log('当前执行栈中同步代码');
        // })
        // console.log('全局执行栈中同步代码');
        //
        if (this.status === FULFILLED) {// 成功态
            return newPromise = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        const x = onFulfilled(this.value);
                        // 新的promise resolve 上一个onFulfilled的返回值
                        this.resolvePromise(newPromise, x, resolve, reject)
                    } catch (e) {
                        // 捕获前面onFulfilled中抛出的异常 then(onFulfilled, onRejected);
                        reject(e);
                    }
                })
            })
        }
        if (this.status === REJECTED) {// 失败态
            return newPromise = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        const x = onRejected(this.reason);
                        this.resolvePromise(newPromise, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
            })
        }
        if (this.status === PENDING) {// 等待态
            // 当异步调用resolve/rejected时 将onFulfilled/onRejected收集暂存到集合中
            return newPromise = new Promise((resolve, reject) => {
                this.onFulfilledCallbacks.push(value => {
                    try {
                        const x = onFulfilled(value);
                        this.resolvePromise(newPromise, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
                this.onRejectedCallbacks.push(reason => {
                    try {
                        const x = onRejected(reason);
                        this.resolvePromise(newPromise, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
            })
        }

    }

    // 用于promise方法链时 捕获前面onFulfilled/onRejected抛出的异常
    catch(onRejected) {
        return this.then(null, onRejected);
    }

    gen(length, resolve) {
        let count = 0;
        const values = [];
        return function (i, value) {
            values[i] = value;
            if (++count === length) {
                resolve(values);
            }
        }
    }

    /**
     * Promise.all Promise进行并行处理
     * 参数: promise对象组成的数组作为参数
     * 返回值: 返回一个Promise实例
     * 当这个数组里的所有promise对象全部变为resolve状态的时候,才会resolve。
     */
    static all(promises) {
        return new Promise((resolve, reject) => {
            let done = this.gen(promises.length, resolve);
            promises.forEach((promise, index) => {
                promise.then((value) => {
                    done(index, value)
                }, reject)
            })
        })
    }

    /**
     * Promise.race
     * 参数: 接收 promise对象组成的数组作为参数
     * 返回值: 返回一个Promise实例
     * 只要有一个promise对象进入 FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理(取决于哪一个更快)
     */
    static race(promises) {
        return new Promise((resolve, reject) => {
            promises.forEach(promise => {
                promise.then(resolve, reject);
            });
        });
    }

    static resolve(value) {
        return new Promise(resolve => {
            resolve(value);
        });
    }

    static reject(reason) {
        return new Promise((resolve, reject) => {
            reject(reason);
        });
    }

    /**
     * 基于Promise实现Deferred的
     * Deferred和Promise的关系
     * - Deferred 拥有 Promise
     * - Deferred 具备对 Promise的状态进行操作的特权方法(resolve reject)
     *
     *参考jQuery.Deferred
     *url: http://api.jquery.com/category/deferred-object/
     */
    static deferred() {
        const defer = {};
        defer.promise = new Promise((resolve, reject) => {
            defer.resolve = resolve;
            defer.reject = reject;
        })
        return defer;
    }

}

// 以下运行结果与es6的promise存在细微差异
// 可以查看这篇文章 https://mp.weixin.qq.com/s/e1-Y8Y40eyqN5gudwBvUqw
/*Promise.resolve().then(() => {
    console.log(0);
    return Promise.resolve(4);
}).then((res) => {
    console.log(res)
})

Promise.resolve().then(() => {
    console.log(1);
}).then(() => {
    console.log(2);
}).then(() => {
    console.log(3);
}).then(() => {
    console.log(5);
}).then(() =>{
    console.log(6);
})*/

/*
* 检测 npm install promises-aplus-tests -g
* promises-aplus-tests promise_es6.js
* */

module.exports = Promise;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值