前端面试题:实现批量请求数据,并控制请求并发数量,最后所有请求结束之后,执行callback回调函数

const allRequest = [
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=1",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=2",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=3",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=4",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=5",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=6",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=7",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=8",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=9",
  "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=10",
];

function sendRequest(urls, max, callbackFunc) {
  const REQUEST_MAX = max;
  const TOTAL_REQUESTS_NUM = urls.length;
  const blockQueue = []; // 等待排队的那个队列
  let currentReqNumber = 0; // 现在请求的数量是
  let numberOfRequestsDone = 0; // 已经请求完毕的数量是
  const results = new Array(TOTAL_REQUESTS_NUM).fill(false); // 所有请求的返回结果,先初始化上

  async function init() {
    for (let i = 0; i < urls.length; i++) {
      request(i, urls[i]);
    }
  }

  async function request(index, reqUrl) {
    // 这个index传过来就是为了对应好哪个请求,
    // 放在对应的results数组对应位置上的,保持顺序
    if (currentReqNumber >= REQUEST_MAX) {
      await new Promise((resolve) => blockQueue.push(resolve)); // 阻塞队列增加一个 Pending 状态的 Promise,
      // 进里面排队去吧,不放你出来,不resolve你,你就别想进行下面的请求
    }
    reqHandler(index, reqUrl); // {4}
  }

  async function reqHandler(index, reqUrl) {
    currentReqNumber++; // {5}
    try {
      const result = await fetch(reqUrl);
      results[index] = result;
    } catch (err) {
      results[index] = err;
    } finally {
      currentReqNumber--;
      numberOfRequestsDone++;
      if (blockQueue.length) {
        // 每完成一个就从阻塞队列里剔除一个
        blockQueue[0](); // 将最先进入阻塞队列的 Promise 从 Pending 变为 Fulfilled,
        // 也就是执行resolve函数了,后面不就能继续进行了嘛
        blockQueue.shift();
      }
      if (numberOfRequestsDone === TOTAL_REQUESTS_NUM) {
        callbackFunc(results);
      }
    }
  }

  init();
}

sendRequest(allRequests, 2, (result) => console.log(result));


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值