任务队列 并发限制

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

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

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

    function next() {
      const index = currentIndex;
      currentIndex++;
      console.log("index", index); // 0,1,2,3,4,5,6
      
      if (!result.includes(false)) {
        resolve(result);
      }
      // 三个(limit=3)分支最后均会执行一次多余的.then(next), 需要阻止 
      if (index >= payloadList.length) {
        return;
      }

      handler(payloadList[index])
        .then((res) => (result[index] = res))
        .catch((err) => (result[index] = err))
        .then(next);
    }
  });
}

const payloadList = [1, 2, 3, 4];
const mapper = (value) =>
  new Promise((resolve, reject) => setTimeout(() => resolve(value), 1000));

multiRequestWithLimit(payloadList, mapper).then((res) =>
  console.log("res", res)
);