// IDs we want to fetch
const userIds = [1, 2, 3, 4, 5];
// Final results array
const results = [];
// Function to fetch a single user
async function fetchUser(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${id}`
);
return response.json();
}
// Promise Pool
async function promisePool(ids, limit) {
let index = 0;
async function worker() {
while (index < ids.length) {
// Take next available ID
const currentIndex = index++;
// Current ID
const id = ids[currentIndex];
console.log(`Fetching User ${id}`);
// Wait for API response
const user = await fetchUser(id);
// Store result at correct position
results[currentIndex] = user;
console.log(`Completed User ${id}`);
}
}
// Create workers
const workers = Array(limit)
.fill(null)
.map(() => worker());
// Wait for all workers
await Promise.all(workers);
return results;
}
// Run with max 2 concurrent requests
promisePool(userIds, 2)
.then(data => {
console.log("Final Results");
console.log(data);
})
.catch(console.error);

Promise.any vs Promise.race

Promise.any() : Returns the first successful promise. Ignores rejected promises.

Promise.race(), after the first promise settles, all other promise results are ignored by race().


Leave a comment

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby