我们不是年复一年的老去,而是日复一日的焕然一新。(送给自己,也送个你们【娇羞脸】)
我很早就有手动实现Promise的想法,拖延了很久,终于在周末处女座情节爆发,硬扛了好久,结果越写越多,自己写了一般结果发现想的还是不周全。然后查阅了一些资料,遂发现规范,也参考了一些实现,受益颇多。
说到Promise,我们能想到什么?
由其自身的三个状态出发(pending,fulfilled,reject),不管函数嵌套几层,函数的过程只需要维护这几个状态,从这个思路出发,因此可以设计成一个状态机。
Version1:
const PENDING = "pending";const FULFILLED = "fulfilled";const REJECTED = "rejected";function Promise(executor) { let self = this.; self.status = PENDING; self.value = undefined; function resolve(value) { if(self.status === PENDING){ self.status = FULFILLED; self.value = value; } } function reject(reason) { if(self.status === PENDING){ self.status = REJECTED; self.value = reason } } try{ exectutor(resolve ,reject) }catch(e) { reject(e) }}Promise.prototype.then = function(onFulfilled, onRejected) { let self = this; if(self.status === FULFILLED){ onFulfilled(self.value); } if(self.status === REJECTED){ onRejected(self.value) }}复制代码
嗯哼,可以了么?貌似并没有那么简单,虽然同步能执行下去,但是当异步操作时,譬如 Version2(Promise主体部分优化)
new Promsie(function(resolve, reject){ resolve(2) ).then(function(data){ console.log(data) },function(reason){ console.log(reason) })}) //输出2new Promsie(function(resolve, reject){ setTimeout(function(){ resolve(2) }).then(function(data){ console.log(data) },function(reason){ console.log(reason) })}) //无输出复制代码
为什么呢?在异步操作还没有返回的时候,函数已经运行完then部分,而此刻返回resolve(1),已经没有意义
怎么解决呢?观察者(发布订阅)模式模式应运而生。这边先声明两个数组onResolveCallBacks,onRejectCallBacks分别保存成功失败的方法,当状态机变化的时候,依次遍历执行数组中的方法
const PENDING = "pending";const FULFILLED = "fulfilled";const REJECTED = "rejected";function Promise(executor) { let self = this.; self.status = PENDING; self.value = undefined; //添加的数组 self.onResolveCallBacks = []; self.onRejectCallBacks = []; function resolve(value) { if(self.status === PENDING){ self.status = FULFILLED; self.value = value; self.onResolveCallBacks.forEach(cb=>cb(self.value)); } } function reject(reason) { if(self.status === PENDING){ self.status = REJECTED; self.value = reason; self.onRejectCallBacks.forEach(cb=>cb(self.value)); } } try{ exectutor(resolve ,reject) }catch(e) { reject(e) }}Promise.prototype.then = function(onFulfilled, onRejected) { let self = this; if(self.status === FULFILLED){ onFulfilled(self.value); } if(self.status === REJECTED){ onRejected(self.value) }}复制代码
现在我们异步操作也能准确了实现了,然后咧~Promise的精髓,链式调用貌似还是不能准确支持,要在then方法之后还能继续调用then,那恐怕解铃还需系铃人了,在then执行完之后再返回一个Promise不就行了么? Version2(then部分优化)
Promise.prototype.then(onFulfilled, onRejected) { let self = this; if(self.status === FULFILLED){ return new Promise((resolve, reject)=>{ let x = onFulfilled(self.value); resolve(x) }) } if(self.status === REJECTED){ return new Promise((resolve, reject)=>{ let x = onRejected(self.value); reject(x) }) } if(self.status === PENDING){ return new Promise(function(resolve, reject){ self.onResolvedCallBacks.push(function(){ let x = onFulfilled(self.value); resolve(x) }) self.onRejectedCallBacks.push(function(){ let x = onFulfilled(self.value); resolve(x) }) }) }}复制代码
看当前的代码貌似很完美了,但是如果then的成功函数onFulfilled要是返回一个Promise怎么办
return new Promise(function(resolve,reject){ self.onResolveCallBacks.push(function(){ let x = onFulfilled(self.value); // 判断返回值是否是Promise,是的话调用thenable方法 if(x instanceof Promise){ x.then(resolve,reject) }else{ resolve(x); } }); self.onRejectCallBacks.push(function(){ let x = onRejected(self.reason); if(x instanceof Promise){ x.then(resolve,reject); }else{ reject(x); } });})复制代码
关于Promise的实现确实包含了很多知识点,譬如Event Loop,递归等等,此处先做个铺垫,先上个基础版本的实现,后续待篇二分解 VERSION3(基础版本API终版)
const PENDING = 'pending';//初始态const FULFILLED = 'fulfilled';//初始态const REJECTED = 'rejected';//初始态function Promise(executor){ let self = this;//先缓存当前promise实例 self.status = PENDING;//设置状态 //定义存放成功的回调的数组 self.onResolvedCallbacks = []; //定义存放失败回调的数组 self.onRejectedCallbacks = []; //当调用此方法的时候,如果promise状态为pending,的话可以转成成功态,如果已经是成功态或者失败态了,则什么都不做 //2.1 function resolve(value){ //2.1.1 if(value!=null &&value.then&&typeof value.then == 'function'){ return value.then(resolve,reject); } //如果是初始态,则转成成功态 //为什么要把它用setTimeout包起来 setTimeout(function(){ if(self.status == PENDING){ self.status = FULFILLED; self.value = value;//成功后会得到一个值,这个值不能改 //调用所有成功的回调 self.onResolvedCallbacks.forEach(cb=>cb(self.value)); } }) } function reject(reason){ //2.1.2 setTimeout(function(){ //如果是初始态,则转成失败态 if(self.status == PENDING){ self.status = REJECTED; self.value = reason;//失败的原因给了value self.onRejectedCallbacks.forEach(cb=>cb(self.value)); } }); } try{ //因为此函数执行可能会异常,所以需要捕获,如果出错了,需要用错误 对象reject executor(resolve,reject); }catch(e){ //如果这函数执行失败了,则用失败的原因reject这个promise reject(e); };}function resolvePromise(promise2,x,resolve,reject){ if(promise2 === x){ return reject(new TypeError('循环引用')); } let called = false;//promise2是否已经resolve 或reject了 if(x instanceof Promise){ if(x.status == PENDING){ x.then(function(y){ resolvePromise(promise2,y,resolve,reject); },reject); }else{ x.then(resolve,reject); } //x是一个thenable对象或函数,只要有then方法的对象, }else if(x!= null &&((typeof x=='object')||(typeof x == 'function'))){ //当我们的promise和别的promise进行交互,编写这段代码的时候尽量的考虑兼容性,允许别人瞎写 try{ let then = x.then; if(typeof then == 'function'){ //有些promise会同时执行成功和失败的回调 then.call(x,function(y){ //如果promise2已经成功或失败了,则不会再处理了 if(called)return; called = true; resolvePromise(promise2,y,resolve,reject) },function(err){ if(called)return; called = true; reject(err); }); }else{ //到此的话x不是一个thenable对象,那直接把它当成值resolve promise2就可以了 resolve(x); } }catch(e){ if(called)return; called = true; reject(e); } }else{ //如果X是一个普通 的值,则用x的值去resolve promise2 resolve(x); }}//onFulfilled 是用来接收promise成功的值或者失败的原因Promise.prototype.then = function(onFulfilled,onRejected){ //如果成功和失败的回调没有传,则表示这个then没有任何逻辑,只会把值往后抛 //2.2.1 onFulfilled = typeof onFulfilled == 'function'?onFulfilled:function(value){ return value}; onRejected = typeof onRejected == 'function'?onRejected:reason=>{throw reason}; //如果当前promise状态已经是成功态了,onFulfilled直接取值 let self = this; let promise2; if(self.status == FULFILLED){ return promise2 = new Promise(function(resolve,reject){ setTimeout(function(){ try{ let x =onFulfilled(self.value); //如果获取到了返回值x,会走解析promise的过程 resolvePromise(promise2,x,resolve,reject); }catch(e){ //如果执行成功的回调过程中出错了,用错误原因把promise2 reject reject(e); } }) }); } if(self.status == REJECTED){ return promise2 = new Promise(function(resolve,reject){ setTimeout(function(){ try{ let x =onRejected(self.value); resolvePromise(promise2,x,resolve,reject); }catch(e){ reject(e); } }) }); } if(self.status == PENDING){ return promise2 = new Promise(function(resolve,reject){ self.onResolvedCallbacks.push(function(){ try{ let x =onFulfilled(self.value); //如果获取到了返回值x,会走解析promise的过程 resolvePromise(promise2,x,resolve,reject); }catch(e){ reject(e); } }); self.onRejectedCallbacks.push(function(){ try{ let x =onRejected(self.value); resolvePromise(promise2,x,resolve,reject); }catch(e){ reject(e); } }); }); }}module.exports = Promise;复制代码