Last active
January 24, 2023 14:17
-
-
Save Maximization/1200ed88d82ac935841cc4748a71f65f to your computer and use it in GitHub Desktop.
A working example of using iterators to implement a mapLimit utility function
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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