手写promise.all

  1. function PromiseAll(promiseArray){
  2. retrun new Promise((resolve,reject)=>{
  3. if(!Array.isArray(promiseArray)){
  4. return reject(new Error('传入的参数必须是数组'))
  5. }
  6. const res = [];
  7. for(let i = 0;i<promiseNums;i++){
  8. const isPromise = Object.prototype.toString.call(promiseArray[i]==='[object Promise]')
  9. if(isPromise){
  10. promiseArray[i].then(result=>{
  11. res.push(result);
  12. })
  13. }else{
  14. res.push(promiseArray[i]);
  15. }
  16. }
  17. })
  18. }
  19. //不需要判断
  20. function PromiseAll(promiseArray){
  21. retrun new Promise((resolve,reject)=>{
  22. if(!Array.isArray(promiseArray)){
  23. return reject(new Error('传入的参数必须是数组'))
  24. }
  25. const res = [];
  26. const promiseNums = primiseArray.length;
  27. for(let i = 0;i<promiseNums;i++){
  28. Promiser.resolve(promoiseArray[i]).then(value=>{
  29. res.push(value);
  30. if(res.length===promiseNums){
  31. resolve(res);
  32. }
  33. })
  34. }
  35. })
  36. }
  37. //需要顺序保持一致
  38. function PromiseAll(promiseArray){
  39. retrun new Promise((resolve,reject)=>{
  40. if(!Array.isArray(promiseArray)){
  41. return reject(new Error('传入的参数必须是数组'))
  42. }
  43. const res = [];
  44. const promiseNums = primiseArray.length;
  45. let counter = 0;
  46. for(let i = 0;i<promiseNums;i++){
  47. Promise.resolve(promoiseArray[i]).then(value=>{
  48. counter++;
  49. res[i] = value;
  50. // 不能通过.length判断
  51. if(counter === promiseNums){
  52. reolve(res);
  53. }
  54. }).catch(e=>rejct(e))
  55. }
  56. })
  57. }

Promise缓存

  1. const cacheMap = new Map();
  2. //装饰器模式
  3. function enableCache(target,name,descriptor){
  4. const val = descriptor.value;
  5. descriptor.value = async function(..args){
  6. const cacheKey = name + JSON.stringify(args);
  7. if(!cacheMap.get(cacheKey)){
  8. const cacheValue = Promise.resolve(val.apply(this,args)).catch(_=>{
  9. cacheMap.set(cacheKey.null);
  10. })
  11. cacheMap.set(cacheKey,cacheValue);
  12. }
  13. return cacheMap.get(cacheKey);
  14. }
  15. return descriptor
  16. }
  17. @enableCache
  • 考虑时效