Skip to content

Instantly share code, notes, and snippets.

@cstroliadavis
Created July 29, 2022 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cstroliadavis/0a9aba55753ca923e09424d1a63eba4d to your computer and use it in GitHub Desktop.
Save cstroliadavis/0a9aba55753ca923e09424d1a63eba4d to your computer and use it in GitHub Desktop.
Adds a meterMap method to an array to help throttle requests
// 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