Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function somelazyfunction() {
- return new Promise((res, rej) => {
- setTimeout(() => {
- res('hello');
- }, 5000);
- });
- }
- function controlledFetch(limit) {
- const queue = [];
- let curr = 0;
- function recursiveCheck() {
- if (curr < limit) {
- curr++;
- if (queue.length > 0) {
- const obj = queue.pop();
- somelazyfunction(obj.url).then((response) => {
- curr--;
- recursiveCheck();
- obj.resolve(response);
- });
- }
- }
- }
- return (url) => {
- return new Promise((resolve, reject) => {
- queue.push({url, resolve, reject});
- recursiveCheck();
- });
- }
- }
- _fetch = controlledFetch(5);
- _fetch('1').then(() => console.log(1));
- _fetch('2').then(() => console.log(2));
- _fetch('3').then(() => console.log(3));
- _fetch('4').then(() => console.log(4));
- _fetch('5').then(() => console.log(5));
- _fetch('6').then(() => console.log(6));
- _fetch('7').then(() => console.log(7));
- _fetch('8').then(() => console.log(8));
- _fetch('9').then(() => console.log(9));
- _fetch('10').then(() => console.log(10));
Add Comment
Please, Sign In to add comment