并发请求

    预计阅读时间: 小于 1 分钟
    /**
     * @param {string[]} urls 待请求的url数组
     * @param {number} maxNum 最大并发数
     */
    function concurRequest(urls, maxNum) {
      if (urls.length === 0) return Promise.resolve([])
      return new Promise(resolve => {
        let index = 0; // 指向下一个请求的url对应的索引
        const result = []; // 存放请求结果
        let count = 0; // 当前已完成的请求数
        async function _request() {
          const i = index;
          const url = urls[index]
          index++;
          try {
            const resp = await fetch(url);
            result[i] =  resp;
          } catch (err) {
            result[i] = err;
          } finally {
            count++;
            if (count === urls.length) {
              resolve(result);
            }
            if (index < urls.length) {
              _request();
            }
          }
        }
        for (let i = 0; i < Math.min(urls.length, maxNum); i++) {
          _request();
        }
      });
    }