// IDs we want to fetchconst userIds = [1, 2, 3, 4, 5];// Final results arrayconst results = [];// Function to fetch a single userasync function fetchUser(id) { const response = await fetch( `https://jsonplaceholder.typicode.com/users/${id}` ); return response.json();}// Promise Poolasync 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 requestspromisePool(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