对Promise源码的明白

媒介

Promise作为一种异步处置惩罚的解决方案,以同步的写作体式格局来处置惩罚异步代码。本文只触及Promise函数和then要领,对其他要领(如catch,finally,race等)暂不研讨。起首,看下Promise的运用场景。

运用场景

例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函数都是异步实行的,其他都是同步实行。

经由历程它的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(失利)。

that.onFulfilledCallbacks这个数组就是存储then要领中的回调函数。实行reject函数为何是异步的,就是因为内里有setTimeout这个函数。当reject实行的时刻,内里的 pending状况->fulfilled状况,转变以后没法再次转变状况了。

然后实行onFulfilledCallbacks内里经由历程then注册的回调函数。因为resolve实行的时刻是异步的,所以还没实行resolve内里详细的代码时刻,已经由历程then要领,把then中回调函数给注册到了
onFulfilledCallbacks中,所以才可以实行onFulfilledCallbacks内里的回调函数。

我们看下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历程以下所示:

《对Promise源码的明白》

在上图第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: "男"}
});

《对Promise源码的明白》

总之,挪用Promise2中的resolve要领,就会把数据通报给Promise2中的then中回调函数。

resolve中的值几种状况:

  • 1.一般值
  • 2.promise对象
  • 3.thenable对象/函数

假如resolve(promise对象),怎样处置惩罚?

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

《对Promise源码的明白》

跟我们适才处置惩罚的返回值是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值
    终究为基础范例或许函数或许对象中的某一种
    原文作者:泪眼朦胧
    原文地址: https://segmentfault.com/a/1190000017179185
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞