Skip to content

Latest commit

 

History

History
executable file
·
41 lines (33 loc) · 925 Bytes

批量请求函数.md

File metadata and controls

executable file
·
41 lines (33 loc) · 925 Bytes

前言

实现一个批量请求函数, 能够限制并发量:

  • 要求最大并发数 maxNum
  • 每当有一个请求返回,就留下一个空位,可以增加新的请求
  • 所有请求完成后,结果按照 urls 里面的顺序依次打出

实现

function multiRequest(urls, maxNum) {
  const results = [];
  let currentIndex = 0;
  let currentRequests = 0;

  function doRequest(url) {
    currentRequests++;
    const i = currentIndex;
    return request(url).then((result) => {
      results[i] = result;
      currentRequests--;
      tryNextRequest();
    });
  }

  function tryNextRequest() {
    while (currentRequests < maxNum && currentIndex < urls.length) {
      doRequest(urls[currentIndex]);
      currentIndex++;
    }

    if (currentIndex === urls.length && currentRequests === 0) {
      // All requests are completed
      console.log(results);
    }
  }

  tryNextRequest();
}