Promise的源码分析

本篇文章不科普Promise,是看了其余做者写的Promise源码实现,通过几天时间针对固定的实例,大概弄明白了Promise的实现思路,特此来记录一下本身的想法,有不正确的地方,欢迎指正。javascript

先贴一下我分析的源码及demohtml

Promise源码

javascript
/**
 * Promise 实现 遵循promise/A+规范
 * Promise/A+规范译文:
 * https://malcolmyu.github.io/2015/06/12/Promises-A-Plus/#note-4
 */

// promise 三个状态
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function Promise(excutor, name) {
    let that = this; // 缓存当前promise实例对象
    that.status = PENDING; // 初始状态
    that.value = undefined; // fulfilled状态时 返回的信息
    that.reason = undefined; // rejected状态时 拒绝的缘由
    that.onFulfilledCallbacks = []; // 存储fulfilled状态对应的onFulfilled函数
    that.onRejectedCallbacks = []; // 存储rejected状态对应的onRejected函数
    that.name = name;
    function resolve(value) { // value成功态时接收的终值
        if(value instanceof Promise) {
            return value.then(resolve, reject);
        }

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

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

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

    // 捕获在excutor执行器中抛出的异常
    // new Promise((resolve, reject) => {
    //     throw new Error('error in excutor')
    // })
    try {
        excutor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}


/**
 * [注册fulfilled状态/rejected状态对应的回调函数]
 * @param  {function} onFulfilled fulfilled状态时 执行的函数
 * @param  {function} onRejected  rejected状态时 执行的函数
 * @return {function} newPromsie  返回一个新的promise对象
 */
Promise.prototype.then = function(onFulfilled, onRejected, name) {
    const that = this;
    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 由pending状态 => 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('全局执行栈中同步代码');
    //

    return newPromise = new Promise((resolve, reject) => {
        if(that.status === FULFILLED) {// 成功态
            setTimeout(() => {
                try{
                    let x = onFulfilled(that.value);
                    resolvePromise(newPromise, x, resolve, reject); // 新的promise resolve 上一个onFulfilled的返回值
                } catch(e) {
                    reject(e); // 捕获前面onFulfilled中抛出的异常 then(onFulfilled, onRejected);
                }
            }, name);
        }else if(that.status === REJECTED) {
            setTimeout(() => {
                try {
                    let x = onRejected(that.reason);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        }else if(that.status === PENDING) {
            // 当异步调用resolve/rejected时 将onFulfilled/onRejected收集暂存到集合中
            that.onFulfilledCallbacks.push((value) => {
                setTimeout(() => {
                    try {
                        let x = onFulfilled(value);
                        resolvePromise(newPromise, x, resolve, reject);
                    } catch(e) {
                        reject(e);
                    }
                })
            });
            that.onRejectedCallbacks.push((reason) => {
                setTimeout(() => {
                    try {
                        let x = onRejected(reason);
                        resolvePromise(newPromise, x, resolve, reject);
                    } catch(e) {
                        reject(e);
                    }
                })
            });
        }
    }, name)
};

/**
 * 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方法
 */
function resolvePromise(promise2, x, resolve, reject) {
    let self = this;
    //PromiseA+ 2.3.1
    if (promise2 === x) {
        reject(new TypeError('Chaining cycle'));
    }
    if (x && typeof x === 'object' || typeof x === 'function') {
        let used; //PromiseA+2.3.3.3.3 只能调用一次
        try {
            let then = x.then;
            if (typeof then === 'function') {
                //PromiseA+2.3.3
                then.call(x, (y) => {
                    //PromiseA+2.3.3.1
                    if (used) return;
                    used = true;
                    resolvePromise(promise2, y, resolve, reject);
                }, (r) => {
                    //PromiseA+2.3.3.2
                    if (used) return;
                    used = true;
                    reject(r);
                }, x.name);

            }else{
                //PromiseA+2.3.3.4
                if (used) return;
                used = true;
                resolve(x);
            }
        } catch (e) {
            //PromiseA+ 2.3.3.2
            if (used) return;
            used = true;
            reject(e);
        }
    } else {
        //PromiseA+ 2.3.3.4
        resolve(x);
    }
}

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

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

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

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

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

Promise.reject = function (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/
 */
Promise.deferred = function() { // 延迟对象
    let defer = {};
    defer.promise = new Promise((resolve, reject) => {
        defer.resolve = resolve;
        defer.reject = reject;
    });
    return defer;
}

/**
 * Promise/A+规范测试
 * npm i -g promises-aplus-tests
 * promises-aplus-tests Promise.js
 */

// try {
//   module.exports = Promise
// } catch (e) {
// }
复制代码
html代码
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Promise</title>
</head>
<script type="text/javascript" src="./promise.js"></script>
<body>


<script type="text/javascript">
	function runAsync1(){
    var p = new Promise(function(resolve, reject){
        setTimeout(function(){
            console.log('异步任务1执行完成');
            resolve('随便什么数据1');
        }, 1000);
    }, "runAsync1");
    return p;
}
function runAsync2(){
    var p = new Promise(function(resolve, reject){
        //作一些异步操做
        setTimeout(function(){
            console.log('异步任务2执行完成');
            resolve('随便什么数据2');
        }, 2000);
    }, "runAsync2");
    return p;            
}
function runAsync3(){
    var p = new Promise(function(resolve, reject){
        //作一些异步操做
        setTimeout(function(){
            console.log('异步任务3执行完成');
            resolve('随便什么数据3');
        }, 2000);
    });
    return p;            
}

runAsync1()
.then(function(data){
    console.log(data);
    return runAsync2();
}, ()=>{},"第一个then")
.then(function(data){
    console.log(data);
    // return runAsync3();
}, ()=>{},"第二个then");
// .then(function(data){
//     console.log(data);
// });

</script>
</body>
</html>
复制代码

由于在分析代码的过程当中,开始this还能知道是哪一个this,可是看到循环调用resolvePromise函数的时候就完全被this战胜了,因此每次调用Promise的时候都添加了name参数,方便分析源码。java

总结一下实现的总体思路:jquery

  1. Promise函数:传递一个excutor执行函数,并执行excutor(resolve, reject)
  2. then函数:参数是onFulfilled 和 onRejected,返回一个新的newPromise,并将resolve时调用的函数push到onFulfilledCallbacks数组中,这个函数主要包含了
try {
    let x = onFulfilled(value);
    resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
    reject(e);
}
复制代码

在执行resolve时,执行onFulfilledCallbacks中push的函数,若是onFulfilled函数返回一个promise对象x,则执行x.then为x中添加callback函数。git

若是想真正弄明白promise的实现思路,仍是须要本身亲自打断点走几遍的。es6

相关文章
相关标签/搜索