对Promise源码的理解

前言

Promise做为一种异步处理的解决方案,以同步的写做方式来处理异步代码。本文只涉及Promise函数和then方法,对其余方法(如catch,finally,race等)暂不研究。首先,看下Promise的使用场景。ajax

使用场景

例1 普通使用数组

new Promise((resolve, reject) => {
    console.log(1);
    resolve(2);
    console.log(3);
    }).then(result => {
         console.log(result);
    }).then(data => {
         console.log(data);
    });

// =>  1
// =>  3
// =>  2
// =>  undefined

构造函数Promise接受一个函数参数exactor,这个函数里有两个函数参数(resolve和reject),在实例化以后,当即执行这个exactor,须要注意的是,exactor里面除了resolve和reject函数都是异步执行的,其余都是同步执行。promise

经过它的then方法【注册】promise异步操做成功时执行的回调,意思就是resolve传入的数据会传递给then中回调函数中的参数。能够理解为,先把then中回调函数注册到某个数组里,等执resolve时候,再执行这个数组中的回调函数。若是then中的回调函数没有返回值,那么下个then中回调函数的参数为undefined。 then方法注册回调函数,也能够理解为【发布订阅模式】。缓存

例2 Promise与原生ajax结合使用异步

function getUrl(url) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open('GET', url, true);
        xhr.onload = function () {
          if (/^2\d{2}$/.test(this.status) || this.status === 304 ) {
               resolve(this.responseText, this)
          } else {
               let reason = {
                    code: this.status,
                    response: this.response
               };
               reject(reason, this);
          }
        };
        xhr.send(null);
    });
}

getUrl('./a.text')
.then(data => {console.log(data)});

例3 Promise与$.ajax()结合使用函数

var getData=function(url) {
    return new Promise((resolve, reject) => {
      $.ajax({ 
          type:'get', 
          url:url, 
          success:function(data){ 
              resolve(data);
          }, 
          error:function(err){ 
              reject(err);
          } 
        });
    });
}
getData('./a.txt')
.then(data => {
    console.log(data);
});

Promise源码分析

首先看一下Promise函数的源码源码分析

function Promise(excutor) {
    let that = this; // 缓存当前promise实例对象
    that.status = PENDING; // 初始状态
    that.value = undefined; // fulfilled状态时 返回的信息
    that.reason = undefined; // rejected状态时 拒绝的缘由
    that.onFulfilledCallbacks = []; // 存储fulfilled状态对应的onFulfilled函数
    that.onRejectedCallbacks = []; // 存储rejected状态对应的onRejected函数

    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) {
                // 只能由pedning状态 => 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) {
                // 只能由pedning状态 => 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);
    }
}

根据上面代码,Promise至关于一个状态机,一共有三种状态,分别是 pending(等待),fulfilled(成功),rejected(失败)。ui

that.onFulfilledCallbacks这个数组就是存储then方法中的回调函数。执行reject函数为何是异步的,就是由于里面有setTimeout这个函数。当reject执行的时候,里面的 pending状态->fulfilled状态,改变以后没法再次改变状态了。this

而后执行onFulfilledCallbacks里面经过then注册的回调函数。由于resolve执行的时候是异步的,因此还没执行resolve里面具体的代码时候,已经经过then方法,把then中回调函数给注册到了
onFulfilledCallbacks中,因此才可以执行onFulfilledCallbacks里面的回调函数。url

咱们看下then又是如何注册回调函数的

/**
 * [注册fulfilled状态/rejected状态对应的回调函数]
 * @param  {function} onFulfilled fulfilled状态时 执行的函数
 * @param  {function} onRejected  rejected状态时 执行的函数
 * @return {function} newPromsie  返回一个新的promise对象
 */
Promise.prototype.then = function(onFulfilled, onRejected) {
    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 由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 (that.status === FULFILLED) { // 成功态
        return newPromise = new Promise((resolve, reject) => {
            setTimeout(() => {
                try{
                    let x = onFulfilled(that.value);
                    resolvePromise(newPromise, x, resolve, reject); // 新的promise resolve 上一个onFulfilled的返回值
                } catch(e) {
                    reject(e); // 捕获前面onFulfilled中抛出的异常 then(onFulfilled, onRejected);
                }
            });
        })
    }

    if (that.status === REJECTED) { // 失败态
        return newPromise = new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    let x = onRejected(that.reason);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        });
    }

    if (that.status === PENDING) { // 等待态
        // 当异步调用resolve/rejected时 将onFulfilled/onRejected收集暂存到集合中
        return newPromise = new Promise((resolve, reject) => {
            that.onFulfilledCallbacks.push((value) => {
                try {
                    //  回调函数
                    let x = onFulfilled(value);
                    // resolve,reject都是newPromise对象下的方法
                    // x为返回值
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
            that.onRejectedCallbacks.push((reason) => {
                try {
                    let x = onRejected(reason);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        });
    }
};

正如以前所说的,先执行then方法注册回调函数,而后执行resolve里面代码(pending->fulfilled),此时执行then时候that.status为pending。

在分析that.status以前,先看下判断onFulfilled的做用

onFulfilled =typeof onFulfilled === "function" ? onFulfilled : value => value;

若是then中并无回调函数的话,自定义个返回参数的函数。至关于下面这种

new Promise((resolve, reject) => {
    resolve('haha');
})
.then()
.then(data => console.log(data)) // haha

即便第一个then没有回调函数,可是经过自定义的回调函数,依然把最开始的数据传递到了最后。

回过头咱们看下then中that.pending 判断语句,发现真的经过onRejectedCallbacks 数组注册了回调函数。

总结下then的特色:

  1. 当status为pending时候,把then中回调函数注册到前一个Promise对象中的onFulfilledCallbacks
  2. 返回一个新的Promise实例对象

整个resolve过程以下所示:

clipboard.png

在上图第5步时候,then中的回调函数就可使用resolve中传入的数据了。那么又把回调函数的
返回值放到resolvePromise里面干吗,这是为了 链式调用。
咱们看下resolvePromise函数

/**
 * 对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) {
    if (promise2 === x) {  // 若是从onFulfilled中返回的x 就是promise2 就会致使循环引用报错
        return reject(new TypeError('循环引用'));
    }

    let called = false; // 避免屡次调用
    // 若是x是一个promise对象 (该判断和下面 判断是否是thenable对象重复 因此无关紧要)
    if (x instanceof Promise) { // 得到它的终值 继续resolve
        if (x.status === PENDING) { // 若是为等待态需等待直至 x 被执行或拒绝 并解析y值
            x.then(y => {
                resolvePromise(promise2, y, resolve, reject);
            }, reason => {
                reject(reason);
            });
        } else { // 若是 x 已经处于执行态/拒绝态(值已经被解析为普通值),用相同的值执行传递下去 promise
            x.then(resolve, reject);
        }
        // 若是 x 为对象或者函数
    } else 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;
                    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 {
        // 基本类型的值(string,number等)
        resolve(x);
    }
}

总结下要处理的返回值的类型:

1. Promise2自己 (暂时没想通)
2. Promise对象实例
3. 含有then方法的函数或者对象
4. 普通值(string,number等)

本身观察上面的代码,咱们发现无论返回值是 Promise实例,仍是基本类型的值,最终都要用Promise2的resolve(返回值)来处理,而后把Promise2的resolve(返回值)中的返回值传递给Promise2的then中的回调函数,这样下去就实现了链式操做。

若是还不懂看下面的代码:

var obj=new Promise((resolve, reject) => {
    resolve({name:'李四'});
});
obj.then(data=>{
    data.sex='男';
    return new Promise((resolve, reject) => {
                resolve(data);
            });
}).then(data => {
   console.log(data); // {name: "李四", sex: "男"}
});

clipboard.png

总之,调用Promise2中的resolve方法,就会把数据传递给Promise2中的then中回调函数。

resolve中的值几种状况:

  • 1.普通值
  • 2.promise对象
  • 3.thenable对象/函数

若是resolve(promise对象),如何处理?

if(value instanceof Promise) {
     return value.then(resolve, reject);
}

clipboard.png

跟咱们刚才处理的返回值是Promise实例对象同样, 最终要把resolve里面数据转为对象或者函数或者基本类型的值

注意:then中回调函数必需要有返回值
var obj=new Promise((resolve, reject) => {
    resolve({name:'张三'});
});
obj.then(data=>{
   console.log(data) // {name:'李四'}
   // 必需要有返回值
}).then(data => {
    console.log(data); // undefined
});

若是then中回调函数没有返回值,那么下一个then中回调函数的值不存在。

总结一下:

  • then方法把then中回调函数注册给上一个Promise对象中的onFulfilledCallbacks数组中,并交由上一个Promise对象处理。
  • then方法返回一个新的Promise实例对象
  • resolve(data)或者resolvePromise(promise2, data, resolve, reject) 中的data值
    最终为基本类型或者函数或者对象中的某一种