Sobes.tech
Middle+

Practical task: implement a function that takes an array of URLs and a limit of concurrent requests, and performs fetch requests with a limit on parallel execution (no more than limit requests at the same time), returning results in the original order.

sobes.tech AI

Answer from AI

To solve a task with a limit on the number of simultaneous fetch requests, you can use a queue and control the number of active promises. Below is an example implementation in JavaScript using async/await:

async function limitedFetch(urls, limit) {
  const results = new Array(urls.length);
  let activeCount = 0;
  let currentIndex = 0;

  return new Promise((resolve, reject) => {
    function next() {
      if (currentIndex === urls.length && activeCount === 0) {
        resolve(results);
        return;
      }

      while (activeCount < limit && currentIndex < urls.length) {
        const index = currentIndex++;
        activeCount++;
        fetch(urls[index])
          .then(res => res.text()) // or res.json() depending on the task
          .then(data => {
            results[index] = data;
          })
          .catch(err => {
            results[index] = err;
          })
          .finally(() => {
            activeCount--;
            next();
          });
      }
    }

    next();
  });
}

In this code, no more than limit requests are run simultaneously, and upon completion of each, the next one from the queue is started. Results are stored in the results array in the original order.