//准备数据,调用方法

  let data = [{ name: 1 }, { name: 2 }, { name: 3 }, { name: 4 }];
  LimitFunc(data, service, 2);

//data:请求所需参数,service:请求回调名称,LimitNum 并发数量

const LimitFunc = async (data, service, LimitNum) => {
  const arrList = []; // 所有的promise
  const running = []; // 正在执行的promise
  for (const item of data) {
    const p = Promise.resolve(service(item)); // Promise.resolve回调函数
    arrList.push(p);
    if (LimitNum <= data.length) {
      // then回调中,当这个promise状态变为fulfilled后,将其从正在执行的promise列表running中删除
      const e = p.then(() => running.splice(running.indexOf(e), 1));
      running.push(e);
      if (running.length >= LimitNum) {
        // running的数量等于限制数时,Promise.race等待某一个promise状态发生变更,
        // 变更后,执行then的回调,将当前promise从running中删除,从下一次for循环中生成新的promise进入running
        await Promise.race(running);
      }
    }
  }
  return Promise.all(arrList);
};

//axios请求

function service(item) {
  return new Promise((resolve) => {
    // axios成功
    axios('url', item).then(() => {
      resolve();
    });
  });
}

Victory
23 声望1 粉丝

专业CV战士