Sobes.tech
Middle+

Implement a fetchAll function that takes an array of URLs and a fetcher, and returns an array of results. How to make parallel and sequential requests?

sobes.tech AI

Answer from AI

javascript // fetcher - function that takes a URL and returns a Promise with the result

// Parallel requests async function fetchAllParallel(urls, fetcher) { const promises = urls.map(url => fetcher(url)); return Promise.all(promises); }

// Sequential requests async function fetchAllSequential(urls, fetcher) { const results = []; for (const url of urls) { const result = await fetcher(url); results.push(result); } return results; }


In the parallel version, all requests are initiated simultaneously, which is faster but can overload the network or server. In the sequential version, requests are made one after another, which can be useful if order matters or if the server limits the number of concurrent connections.