第十二篇 手写原理代码 - 实现一个前端并发控制请求函数

实现并发控制请求函数

/**
 * 并发控制请求函数
 * @param {Array} urls 请求的 URL 数组
 * @param {Number} max 最大并发数
 * @param {Function} callback 请求成功回调函数
 */
async function concurrentRequest(urls, max, callback) {
  const len = urls.length;
  // 用一个数组存储所有的请求结果
  const results = new Array(len);
  // 用一个变量记录已经完成的请求数
  let count = 0;

  // 定义一个请求函数,返回一个 Promise 对象
  function request(url) {
    return new Promise((resolve, reject) => {
      fetch(url)
        .then((res) => res.json())
        .then((data) => {
          resolve(data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  // 利用 while 循环来模拟并发请求过程
  while (count < len) {
    // 判断当前并发数是否已达到最大值,如果未达到则继续发起新的请求
    if (count < max) {
      const index = count;
      count++;
      const url = urls[index];
      try {
        // 调用请求函数并保存请求结果
        const result = await request(url);
        results[index] = result;
        callback && callback(result);
      } catch (err) {
        console.error(`Error occurred when fetching ${url}:`, err);
      }
    } else {
      // 如果当前并发数已经达到最大值,就等待其中的一个请求完成后再继续发起新的请求
      await Promise.race(results.map((p) => p instanceof Promise && p.catch(() => {})));
    }
  }
  return results;
}

使用

const urls = [
  "http://xxa",
  "http://xxb",
  "http://xxc",
  "http://xxd",
  "http://xxe",
  "http://xx1e",
  "http://xx2e",
  "http://xx3e",
  "http://x4xe",
]

// 定义最大并发数
const maxConcurrent = 3;

// 调用 concurrentRequest 函数进行并发控制请求
concurrentRequest(urls, maxConcurrent, (result) => {
  console.log(result);
}).then((results) => {
  console.log('All requests have been completed:', results);
});
posted @ 2023-04-12 12:03  caix-1987  阅读(102)  评论(0)    收藏  举报