深入理解promise底层源码有助于我们更好地理解promise。以下代码可以实现promise的基本功能。
class Promise{// 构造方法constructor(executor){// 添加属性this.PromiseState = "pending";this.PromiseResult = null;this.callbacks = [];// 保存实例对象this的值const self = this; //self _this that// resolve函数function resolve(data) {// 判断状态if (self.PromiseState !== "pending") return;// 1.修改对象的状态(promiseState)self.PromiseState = "fulfilled"; //resolved// 2.设置对象结果值(PromiseResult)self.PromiseResult = data;// 调用成功的回调函数(定时器实现异步回调)setTimeout(()=>{self.callbacks.forEach((item) => {item.onResolved(data);});})}// reject函数function reject(data) {if (self.PromiseState !== "pending") return;// 1.修改对象的状态(promiseState)self.PromiseState = "rejected"; //resolved// 2.设置对象结果值(PromiseResult)self.PromiseResult = data;//执行失败的回调函数(定时器实现异步回调)setTimeout(()=>{self.callbacks.forEach((item) => {item.onRejected(data);});})}try {// 同步调用执行器函数executor(resolve, reject);} catch (e) {reject(e);}}// then方法then(onResolved,onRejected){const self = this;// 判断回调函数参数if(typeof onRejected !=='function'){onRejected=reason=>{throw reason}}if(typeof onResolved !=='function'){onResolved=value=>value}return new Promise((resolve, reject) => {// 封装函数function callback(type){try {//获得回调函数的执行结果let result = type(self.PromiseResult);// 判断if (result instanceof Promise) {//如果是Promise类型的对象result.then((v) => {resolve(v);},(r) => {reject(r);});} else {//结果的对象状态为成功resolve(result);}} catch (e) {reject(e);}}// 调用回调函数 PromiseStateif (this.PromiseState === "fulfilled") {// (定时器实现异步回调)setTimeout(()=>{callback(onResolved)})}if (this.PromiseState === "rejected") {// (定时器实现异步回调)setTimeout(()=>{callback(onRejected)})}// 判断pending状态if (this.PromiseState === "pending") {// 保存回调函数this.callbacks.push({onResolved: function () {callback(onResolved)},onRejected: function () {callback(onRejected)},});}});}// catch方法catch(onRejected){return this.then(undefined,onRejected)}// resolve方法static resolve(value){return new Promise((resolve,reject)=>{if(value instanceof Promise){value.then(v=>{resolve(v)},r=>{reject(r)})}else{resolve(value)}})}// reject方法static reject(reason){return new Promise((resolve,reject)=>{reject(reason)})}// all方法static all(promises){// 返回结果为promise对象return new Promise((resolve,reject)=>{// 声明变量let count=0;let arr=[]// 遍历for(let i=0;i<promises.length;i++){promises[i].then(v=>{// 得知对象的状态为成功// 每个promise对象都成功count++;// 将当前的promise对象成功的结果 存入到数组中arr[i]=vif(count===promises.length){// 修改状态resolve(arr)}},r=>{reject(r)})}})}// race方法static race(promises){return new Promise((resolve,reject)=>{for(let i=0;i<promises.length;i++){promises[i].then(v=>{resolve(v)},r=>{reject(r)})}})}
}