← 返回完整题库
JavaScript困难

Promise 如何限制并发数量?

参考答案

核心:维护"运行中数量 + 等待队列"。

function limit(tasks, max) {
  return new Promise((resolve, reject) => {
    let running = 0, idx = 0, done = 0; const results = [];
    const next = () => {
      if (done === tasks.length) return resolve(results);
      while (running < max && idx < tasks.length) {
        const i = idx++;
        running++;
        Promise.resolve(tasks[i]())
          .then(v => { results[i] = v; })
          .catch(reject)
          .finally(() => { running--; done++; next(); });
      }
    };
    next();
  });
}

要点:

  • 任务以函数形式传入(惰性启动);
  • 一个完成立即补位(而不是分批等待);
  • 保持结果顺序(按索引写回);
  • 任一失败可整体 reject 或用 allSettled 语义;
  • 也可用递归 + 计数器、p-limit 库。

本题来自 计算机知识面试题库,共 921 道题。