Created
April 20, 2022 08:43
-
-
Save andrIvash/e2009f93d81d7d3ec25cc79e8f6321cb to your computer and use it in GitHub Desktop.
schedules running HTTP requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @module | |
* @description It schedules running HTTP requests | |
*/ | |
export const requestsManager = (function() { | |
const waitingQueue = []; | |
const runningQueue = []; | |
const MAX_PARALLEL_REQUESTS = 5; | |
function makeRequest(reqToMake) { | |
if (runningQueue.length < MAX_PARALLEL_REQUESTS) { | |
runRequest(reqToMake); | |
} else { | |
waitingQueue.push(reqToMake); | |
} | |
} | |
function runRequest(reqToMake) { | |
const promise = reqToMake() | |
.then(res => { | |
runningQueue.splice(runningQueue.indexOf(promise), 1); | |
if (waitingQueue?.length) { | |
runRequest(waitingQueue[0]); | |
waitingQueue.splice(0, 1); | |
} | |
return res; | |
}).catch(err => { | |
runningQueue.splice(runningQueue.indexOf(promise), 1); | |
if (waitingQueue?.length) { | |
runRequest(waitingQueue[0]); | |
waitingQueue.splice(0, 1); | |
} | |
}); | |
runningQueue.push(promise); | |
} | |
return { | |
makeRequest | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requestsManager.makeRequest(new Promise((resolve, reject) => { fetch().then((res) => { resolve(res); }).catch((err) => { reject(err); }); }));