对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的特点:
- 当status为pending时候,把then中回调函数注册到前一个Promise对象中的onFulfilledCallbacks
- 返回一个新的Promise实例对象
整个resolve过程如下所示:

在上图第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: "男"}
});
总之,调用Promise2中的resolve方法,就会把数据传递给Promise2中的then中回调函数。
resolve中的值几种情况:
- 1.普通值
- 2.promise对象
- 3.thenable对象/函数
如果resolve(promise对象),如何处理?
if(value instanceof Promise) {
return value.then(resolve, reject);
}
跟我们刚才处理的返回值是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值
最终为基本类型或者函数或者对象中的某一种