任务队列 并发限制

function multiRequestWithLimit(payloadList, handler, limit = 3) {
  // 请求总数量
  const len = payloadList.length;
  // 根据请求数量创建一个数组来保存请求的结果
  const result = new Array(len).fill(false);

  // 当前执行的是第几条
  let index = 0;

  return new Promise((resolve, reject) => {
    for (let i = 0; i < limit; i++) {
      next();
    }

    function next() {
      if (!result.includes(false)) {
        return resolve(result);
      }
      if (index > len - 1) {
        return;
      }
      handler(payloadList[index])
        .then((res) => (result[index] = res))
        .catch((err) => (result[index] = err))
        .finally((final) => {
          console.log("final", final);

          index++;
        })
        .then(next);
    }
  });
}

const payloadList = [1, 2, 3, 4];
const handle = (a) => {
  setTimeout(() => {
    console.log(a);
  }, 200);
};

multiRequestWithLimit(payloadList, handle).then(res => console.log(res))

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享