关于前端:限制数量请求池函数实现

// function createRequestPool(poolSize) {
// }

// const request = createRequestPool(3);
// for (let i = 0; i < 10000; i++) {
//   request('/count').then(xxxx).catch(xxx)
// }

/**
 * 记笔记,待验证
 */
function createRequestPool(poolSize) {
  const reqs = [];
  const temps = [];

  return function (url) {

    function runTask() {

      // 循环增加到长期数组中
      while (reqs.length && temps.length < poolSize) {
        temps.push(reqs.shift());
      }

      // 遍历长期数组,发动申请
      for (let i = 0; i < temps.length; i++) {
        fetch(temps[i].url)
          .then((data) => {
            // 移除以后申请,并返回后果
            temps.splice(temps.indexOf(temps[i]), 1);
            temps[i].resolve(data);

            // 每实现一个,就须要执行队列中的工作
            runTask();
          })
          .catch((err) => {
            // 移除以后申请,并返回后果
            temps.splice(temps.indexOf(temps[i]), 1);
            temps[i].reject(err);
          });
      }
    }

    return new Promise((resolve, reject) => {
      reqs.push({
        url,
        resolve,
        reject
      });

      runTask();
    });
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理