The World of Remnant

限制并发数的Promise.all

const api = (time) => {
  console.log("请求了" + time);
  return new Promise((resolve) =>
    setTimeout(() => {
      resolve(time);
    }, time)
  );
};

const asyncpool = async (requestlist, limit, callback) => {
  const promises = [];
  const pool = new Set();

  for (const request of requestlist) {
    if (pool.size >= limit) {
      await Promise.race(pool).catch((err) => err);
    }
    const promise = request();
    promise.finally(pool.delete(promise));
    pool.add(promise);
    promises.push(promise);
  }
  Promise.allSettled(promises).then(callback, callback);
};

asyncpool(
  [() => api(1000), () => api(2000), () => api(3000), () => api(2500)],
  3,
  (res) => {
    console.log("callback", res);
  }
);