garvitdelhi

Untitled

Jan 31st, 2019
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function somelazyfunction() {
  2.     return new Promise((res, rej) => {
  3.         setTimeout(() => {
  4.             res('hello');
  5.         }, 5000);
  6.     });
  7. }
  8.  
  9. function controlledFetch(limit) {
  10.     const queue = [];
  11.     let curr = 0;
  12.  
  13.     function recursiveCheck() {
  14.         if (curr < limit) {
  15.             curr++;
  16.             if (queue.length > 0) {
  17.                 const obj = queue.pop();
  18.                 somelazyfunction(obj.url).then((response) => {
  19.                     curr--;
  20.                     recursiveCheck();
  21.                     obj.resolve(response);
  22.                 });
  23.             }
  24.         }
  25.     }
  26.  
  27.  
  28.     return (url) => {
  29.         return new Promise((resolve, reject) => {
  30.             queue.push({url, resolve, reject});
  31.             recursiveCheck();
  32.         });
  33.     }
  34. }
  35.  
  36. _fetch = controlledFetch(5);
  37.  
  38. _fetch('1').then(() => console.log(1));
  39. _fetch('2').then(() => console.log(2));
  40. _fetch('3').then(() => console.log(3));
  41. _fetch('4').then(() => console.log(4));
  42. _fetch('5').then(() => console.log(5));
  43. _fetch('6').then(() => console.log(6));
  44. _fetch('7').then(() => console.log(7));
  45. _fetch('8').then(() => console.log(8));
  46. _fetch('9').then(() => console.log(9));
  47. _fetch('10').then(() => console.log(10));
Add Comment
Please, Sign In to add comment