Created
July 29, 2022 19:12
-
-
Save cstroliadavis/0a9aba55753ca923e09424d1a63eba4d to your computer and use it in GitHub Desktop.
Adds a meterMap method to an array to help throttle requests
This file contains 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
// runs a promise that resolves after time in milliseconds. | |
// usage `await pause(1000)` | |
function pause = time => new Promise(resolve => setTimeout(resolve, time)); | |
// adds a "meter" method to an array | |
// a meter is like the freeway metering you see near onramps during peak hours. | |
// It works basically like a Promise.all(arr.map()) function, except that each | |
// mapped item waits `waitTime` milliseconds before actually starting. This helps | |
// throttle throughput to webservices, reducing the chance that they will not be | |
// able to keep up with the concurrent load. | |
// examples: | |
// const myVals = await addMetering(arr, 1000).meterMap(async (item, idx, arr) => { ... do stuff } | |
// OR | |
// addMetering(myArr); | |
// myArr.meterMap(cb, 1500).then(() => do stuff); | |
function addMetering(arr, waitTime) { | |
if(Array.isArray(arr)) { | |
arr.meterMap = async (callback, wait = waitTime) => { | |
const result = []; | |
for(let x = 0; x < arr.length; x++) { | |
await pause(wait); | |
result.push(callback(arr[x], x, arr)); | |
} | |
return Promise.all(result); | |
} | |
} else { | |
throw new TypeError('The first argument must be an array'); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment