手写promise.all
function PromiseAll(promiseArray){retrun new Promise((resolve,reject)=>{if(!Array.isArray(promiseArray)){return reject(new Error('传入的参数必须是数组'))}const res = [];for(let i = 0;i<promiseNums;i++){const isPromise = Object.prototype.toString.call(promiseArray[i]==='[object Promise]')if(isPromise){promiseArray[i].then(result=>{res.push(result);})}else{res.push(promiseArray[i]);}}})}//不需要判断function PromiseAll(promiseArray){retrun new Promise((resolve,reject)=>{if(!Array.isArray(promiseArray)){return reject(new Error('传入的参数必须是数组'))}const res = [];const promiseNums = primiseArray.length;for(let i = 0;i<promiseNums;i++){Promiser.resolve(promoiseArray[i]).then(value=>{res.push(value);if(res.length===promiseNums){resolve(res);}})}})}//需要顺序保持一致function PromiseAll(promiseArray){retrun new Promise((resolve,reject)=>{if(!Array.isArray(promiseArray)){return reject(new Error('传入的参数必须是数组'))}const res = [];const promiseNums = primiseArray.length;let counter = 0;for(let i = 0;i<promiseNums;i++){Promise.resolve(promoiseArray[i]).then(value=>{counter++;res[i] = value;// 不能通过.length判断if(counter === promiseNums){reolve(res);}}).catch(e=>rejct(e))}})}
Promise缓存
const cacheMap = new Map();//装饰器模式function enableCache(target,name,descriptor){const val = descriptor.value;descriptor.value = async function(..args){const cacheKey = name + JSON.stringify(args);if(!cacheMap.get(cacheKey)){const cacheValue = Promise.resolve(val.apply(this,args)).catch(_=>{cacheMap.set(cacheKey.null);})cacheMap.set(cacheKey,cacheValue);}return cacheMap.get(cacheKey);}return descriptor}@enableCache
- 考虑时效
 
