JavaScript手写最大并发请求数?

新手上路,请多包涵
function request1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 100);
  });
}
function request2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2);
    }, 800);
  });
}
function request3() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(3);
    }, 500);
  });
}
function request4() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(4);
    }, 1000);
  });
}

function schedular(max) {
  // TODO
  // code write here
}

const addReques = schedular(2);

addReques(request1).then((res) => {
  console.log(res);
});
addReques(request2).then((res) => {
  console.log(res);
});
addReques(request3).then((res) => {
  console.log(res);
});
addReques(request4).then((res) => {
  console.log(res);
});

如果是schedular传入一个请求数组写最大并发请求数我会,但是这种怎么实现和那个一样的效果?就是这里加入 max 是2,那么最多就只能同时执行2个请求,等到有一个请求完成后,才能进行后面的请求执行

阅读 1.8k
1 个回答

简单实现了一下 可以作为参考

  function schedular(max) {
      const executing = [];
      const fns = new Map();
      const execFn = async () => {
        for (const fn of fns.keys()) {
          if (max <= fns.size) {
            const { resolve, reject } = fns.get(fn);
            const e = Promise.resolve()
              .then(fn)
              .then(resolve, reject)
              .finally(() => {
                executing.splice(executing.indexOf(e), 1);
              });
            executing.push(e);
            if (executing.length >= max) {
              await Promise.race(executing);
            }
          }
        }
      };

      const addReques = (fn) => {
        return new Promise((resolve, reject) => {
            fns.set(fn, { resolve, reject });
        });
      };
      setTimeout(execFn, 0);
      return addReques;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏