Skip to content

Instantly share code, notes, and snippets.

@Maximization
Last active January 24, 2023 14:17
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 Maximization/1200ed88d82ac935841cc4748a71f65f to your computer and use it in GitHub Desktop.
Save Maximization/1200ed88d82ac935841cc4748a71f65f to your computer and use it in GitHub Desktop.
A working example of using iterators to implement a mapLimit utility function
async function mapLimit(array, iterateeFn, concurrency) {
const results = [];
async function runTasks(tasksIterator) {
for (const [index, element] of tasksIterator) {
console.log("Running iterateeFn for element", element);
try {
results[index] = await iterateeFn(element);
} catch (error) {
results[index] = new Error(`Failed with: ${error.message}`);
}
console.log("Finished for element", element);
}
}
const workers = new Array(concurrency).fill(array.entries()).map(runTasks);
await Promise.allSettled(workers);
return results;
}
const userIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
async function iterateeFn(userId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const user = await response.json();
return user.name;
}
const results = await mapLimit(userIds, iterateeFn, 3);
console.log(results);
@Boasbabs
Copy link

Boasbabs commented Jan 24, 2023

Thank you for the help, your approach is very simplistic. I eventually came up with something similar.
I appreciate your effort in helping out.
My implementation: https://codesandbox.io/s/concurrent-tasks-with-a-limit-practice-sqd1xx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment