AI 代码审查实战:保序并发 map 的懒启动与失败收尾

10-19 6阅读

让 AI 写一个带并发上限的异步 map,看起来只需一句提示词。但真正容易埋雷的地方,不在计数器是否减一,而在这个批次最终交付什么:完成次序乱了,输出是否仍对应输入;一个条目失败时,还能不能继续启动;另一个已经运行的条目随后也失败,谁负责把它接住?这些问题若没有先写成契约,几十行看似顺畅的代码就可能在生产环境里留下未处理拒绝。

本文聚焦一次有限批量转换:例如把一组文档片段交给模型处理,最终仍要按原片段顺序拼回结果。我们不设计长期运行的任务队列,而是评审一个 orderedMap 的返回语义、启动时机与失败收尾。所有九个示例都可独立保存为 .mjs 文件,在 Node.js v24.19.0 下运行;每段都包含自己需要的实现与断言,不依赖上一段的变量或外部服务。

AI 代码审查实战:保序并发 map 的懒启动与失败收尾
模型生成的概念插画:并发通道决定谁能开始,固定槽位决定结果放在哪里;关闭入口后仍要照看已经进入通道的工作。画面用于解释关系,不是时序截图。

先写清楚这六条验收条件

  • 只接收有限数组;调用时浅复制槽位,成功返回一个新的等长数组。

  • mapper 接收当前值与原始索引;结果永远写回该索引。

  • 并发上限为正安全整数;正在等待完成的 mapper 数量不超过它。

  • 只有领到名额才调用 mapper,剩余条目保持未启动。

  • 首次捕获失败后停止领取,等待所有已启动工作落定,再以该原始原因拒绝。

  • 空数组不调用 mapper;参数错误也通过返回 Promise 拒绝。

这里的落定包含成功与失败,不意味着所有任务都成功。停止领取也不撤回已经发生的写入,因此该函数不是事务。示例都使用受控 Promise 决定完成顺序,避免用随机延迟证明时序性质。保存任一代码块为 demo.mjs 后,运行下面的命令;普通输出块列出了对应的预期结果。

node --unhandled-rejections=strict demo.mjs

示例一:Promise.all 的结果保序,不能替你限制启动

先拆开两个经常被 AI 混为一谈的问题:结果放在哪个位置,以及任务什么时候开始。原生 Promise.all 已经能保持传入顺序;把异步回调交给数组 map,则会在遍历时依次调用全部回调。请求若在回调中启动,等 Promise.all 接到数组时,启动动作早已发生。给它外面再套一层 await,不会把这些请求变回待领取任务。

ECMAScript 的 Array.prototype.map 算法描述了逐项调用回调;Promise.all 的底层算法则为每个结果保存索引。下面故意反向兑现四个门闩,观察四个回调已经启动,最终数组却仍然有序。这里的 Promise.withResolvers 只是测试开关,不代表已经发起网络请求。

独立文件:01.mjs。

import assert from "node:assert/strict";

const gates = Array.from({ length: 4 }, () => Promise.withResolvers());
const started = [];
const completed = [];
const jobs = [0, 1, 2, 3].map(async index => {
  started.push(index);
  await gates[index].promise;
  completed.push(index);
  return `item-${index}`;
});
assert.deepEqual(started, [0, 1, 2, 3]);
const batch = Promise.all(jobs);
for (const index of [3, 2, 1, 0]) gates[index].resolve();
const result = await batch;
assert.deepEqual(completed, [3, 2, 1, 0]);
assert.deepEqual(result, ["item-0", "item-1", "item-2", "item-3"]);
console.log("started=" + started.join(","));
console.log("completed=" + completed.join(","));
console.log("result=" + result.join(","));

预期输出:

started=0,1,2,3
completed=3,2,1,0
result=item-0,item-1,item-2,item-3

这不是 Promise.all 的缺陷,而是职责边界。它聚合一组值与 Promise,并不接管回调的调用时机。批处理接口应接收原始条目和转换函数,由调度层决定何时调用转换函数。不要先执行所有请求,再把已经运行的 Promise 填入一个声称有并发上限的函数。

示例二:完整实现,把输出位置与完成时间解耦

下面给出本文使用的完整实现。它只处理一次有限数组转换:调用时建立浅快照,分配等长结果数组,每名 worker 一次领取一个索引,完成后才领取下一个。索引领取和自增之间没有 await;在同一个 JavaScript 执行线程内,这段同步代码不会被另一个 worker 插入,因此不会重复领取。输出必须写入 output[index],不能用 push 按完成时间追加。

失败策略也在实现中固定下来:第一个被 worker 捕获的失败关闭领取入口;已经启动的工作继续被观察,直到全部成功或失败;随后整个批次拒绝,并保留第一次捕获的原始原因。注意这是停止新工作并收尾,不是立刻返回错误,也不是中止网络连接。为方便单独复制验证,后面涉及该实现的示例都会完整重复函数。

独立文件:02.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const gates = Array.from({ length: 3 }, () => Promise.withResolvers());
const completed = [];
const batch = orderedMap(["A", "B", "C"], async (value, index) => {
  await gates[index].promise;
  completed.push(index);
  return value.toLowerCase();
}, 3);
for (const index of [2, 0, 1]) gates[index].resolve();
const result = await batch;
assert.deepEqual(completed, [2, 0, 1]);
assert.deepEqual(result, ["a", "b", "c"]);
console.log("completed=" + completed.join(","));
console.log("result=" + result.join(","));

预期输出:

completed=2,0,1
result=a,b,c

保序指最终返回数组的下标对应输入下标,不保证日志、写库、副作用或请求到达服务端的顺序。完成了的后续条目可以先填入自己的位置,没必要等第一项完成才能启动下一项。只有最终交付整个数组时才等待这一批收尾。因此,一个慢任务会拖延最终返回,却不会自动把其他空闲 worker 一并锁住。

示例三:证明懒启动与最大并发,别靠几毫秒延迟猜测

返回值正确,并不足以证明并发控制正确。这个测试同时记录正在运行的数量、峰值、启动索引和每个条目的启动信号。初始只允许第零项与第一项进入;第一项完成后,第二项才获准启动。接着让同一条快通道连续处理更多条目,同时保持第零项未完成,就能区分真正的动态补位与每批固定分组的实现。

测试通过启动通知等待具体事件,不使用 setTimeout,也不假定机器足够快。被测 mapper 的生命周期从 active 增加开始,到 finally 减少结束;外层 worker 只有在返回的 Promise 结束后才继续领任务。这个计数口径必须和业务资源的真实生命周期一致。

独立文件:03.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const gates = Array.from({ length: 5 }, () => Promise.withResolvers());
const entered = Array.from({ length: 5 }, () => Promise.withResolvers());
const started = [];
let active = 0;
let peak = 0;
const batch = orderedMap([0, 1, 2, 3, 4], async (value, index) => {
  started.push(index);
  active += 1;
  peak = Math.max(peak, active);
  entered[index].resolve();
  try {
    await gates[index].promise;
    return value * 10;
  } finally {
    active -= 1;
  }
}, 2);
assert.deepEqual(started, [0, 1]);
gates[1].resolve();
await entered[2].promise;
assert.deepEqual(started, [0, 1, 2]);
gates[2].resolve();
await entered[3].promise;
gates[0].resolve();
await entered[4].promise;
gates[4].resolve();
gates[3].resolve();
assert.deepEqual(await batch, [0, 10, 20, 30, 40]);
assert.equal(peak, 2);
assert.equal(active, 0);
console.log("started=" + started.join(","));
console.log("peak=" + peak + ", active=" + active);

预期输出:

started=0,1,2,3,4
peak=2, active=0

这里的懒启动不是说调用 orderedMap 后什么也不做。它会立即启动不超过上限的初始工作,只把剩余 mapper 调用延后。上限限制的是当前这次调用所观察的 mapper 数量;同时开十个批次,每批上限为二,总量仍可能达到二十。需要跨批次共享额度时,应另设共享调度器,不能把局部上限误当成全局限流。

示例四:首次失败之后,停发新工作并接住在途失败

最危险的 AI 代码常出现在错误路径:某个 Promise 拒绝后马上把外层批次抛掉,剩下的 Promise 没有可靠的观察者;或者清空待办队列,却没有等待已经启动的工作。本文让每个 worker 在自己的 try/catch 内直接 await mapper,业务失败不会逃出 worker。外层 Promise.all 等待的是这些会自行收尾的 worker,而不是一组无人管理的请求。

此例先拒绝第零项,确认第三项尚未启动,而且整个批次仍未结束;再让第一项也拒绝,确认第二个错误被观察但不会覆盖第一个。一次 await Promise.resolve 仅让前面已排入微任务队列的直接 await 拒绝处理先运行;这里没有定时器,也没有用固定次数轮询等待业务完成。

独立文件:04.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const gates = [Promise.withResolvers(), Promise.withResolvers()];
const started = [];
const first = new Error("first failure");
const later = new Error("late failure");
let settled = false;
const batch = orderedMap([0, 1, 2], (_value, index) => {
  started.push(index);
  return gates[index].promise;
}, 2);
const observed = batch.then(
  () => { settled = true; return { ok: true }; },
  reason => { settled = true; return { ok: false, reason }; }
);
gates[0].reject(first);
await Promise.resolve();
assert.deepEqual(started, [0, 1]);
assert.equal(settled, false);
gates[1].reject(later);
const outcome = await observed;
assert.equal(outcome.ok, false);
assert.equal(outcome.reason, first);
assert.deepEqual(started, [0, 1]);
console.log("started=" + started.join(","));
console.log("drained=true, reason=" + outcome.reason.message);

预期输出:

started=0,1
drained=true, reason=first failure

调用方也要及时 await 批次,或者立刻安装拒绝处理器。调度器接住内部在途失败,不等于外层返回的拒绝可以被忽略。用 Node.js 官方命令行文档中的 strict 模式运行测试,能让遗漏的拒绝暴露为进程失败。本实现不为 mapper 私自启动、却没有返回或等待的后台任务负责;那部分必须由 mapper 自己管理。

示例五:同步抛错与假值原因,不能用 error 判断是否失败

JavaScript 允许抛出任何值。AI 常写成 let error,然后用 if (error) 判断失败;一旦原因恰好是 undefined、null、零或空字符串,批次就可能被误报成功。失败状态与失败原因必须独立存储,因此实现中同时保留 stopped 和 firstReason。我们不擅自包装 Error,也不丢失原始原因的身份。

同步抛错发生在 mapper 调用当下,try/catch 直接捕获。这个实现按顺序创建 worker,所以如果首个 mapper 同步抛错,后续 worker 即便被创建,也会看到 stopped,不再领取条目。这和 mapper 返回一个已拒绝 Promise 的时序不同:后者要等 await 的拒绝续体执行,初始窗口中的其他条目可能已经启动。

独立文件:05.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const reasons = [undefined, null, 0, ""];
for (const reason of reasons) {
  const started = [];
  const batch = orderedMap([0, 1, 2], (_value, index) => {
    started.push(index);
    throw reason;
  }, 3);
  const outcome = await batch.then(
    () => ({ ok: true }),
    error => ({ ok: false, error })
  );
  assert.equal(outcome.ok, false);
  assert.equal(outcome.error, reason);
  assert.deepEqual(started, [0]);
}
console.log("falsy reasons preserved=4");
console.log("sync failure starts only index 0");

预期输出:

falsy reasons preserved=4
sync failure starts only index 0

生产日志可以在调用方把非 Error 原因转成便于检索的记录,但调度层不应偷偷改变 API 契约。同步失败、异步拒绝和 thenable 同化失败都应经过同一条停止路径。代码审查时,观察是否存在多个各自更新失败状态的分支;分支越多,越容易出现某个分支忘记禁止补位。

示例六:先验证参数,再谈空数组与超大上限

并发数应是正安全整数。零、负数、小数、无穷大、NaN、字符串以及超出安全整数范围的数都被拒绝,不做隐式类型转换。即使输入为空也先验证参数,否则测试会得到空数组通过、真实数据失败的不一致接口。因为函数本身是 async,这些参数错误表现为返回 Promise 的拒绝,应使用 await 或 assert.rejects 检查。

空数组不调用 mapper,返回新空数组。上限大于输入长度是合法情况,但只创建实际需要的 worker;并发上限为二十而条目只有三个,不会凭空创建二十个执行槽。验证不能替业务做容量规划:非常大的合法上限遇到非常大的数组,仍可能消耗大量内存与连接。

独立文件:06.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

let calls = 0;
const mapper = value => { calls += 1; return value; };
await assert.rejects(orderedMap("abc", mapper, 2), TypeError);
await assert.rejects(orderedMap([], null, 2), TypeError);
for (const invalid of [0, -1, 1.5, Infinity, NaN, "2", Number.MAX_SAFE_INTEGER + 1]) {
  await assert.rejects(orderedMap([], mapper, invalid), RangeError);
}
assert.deepEqual(await orderedMap([], mapper, 2), []);
assert.equal(calls, 0);
assert.deepEqual(await orderedMap([7, 8], mapper, 20), [7, 8]);
assert.equal(calls, 2);
console.log("validation=ok, empty calls=0");
console.log("oversized limit calls=" + calls);

预期输出:

validation=ok, empty calls=0
oversized limit calls=2

这份示例明确只接收数组,没有宣称支持无限迭代器或异步数据流。若需求是边读边处理、边产出结果,还要定义拉取背压、输出缓冲区大小和消费者取消行为。把 Array.from 改成某个迭代器调用并不足以获得完整流式语义,尤其当输入可能无限时。

示例七:输入快照、稀疏槽位与浅复制边界

异步批次运行期间,外部代码可能修改输入数组。实现一开始用 Array.from 建立快照,使条目数量与值槽位固定下来;下面在第一项被门闩阻塞时修改第三项并追加第四项,结果仍依据最初快照。这个策略让一次批次的输入边界易于推理,也避免长度变化导致任务漏跑或多跑。

这里明确把普通稀疏数组的空槽视为 undefined 并执行 mapper,所以不完全复刻原生 map 跳过空槽的行为。快照只是浅复制,数组中的对象引用仍然共享;修改对象内部字段仍可能影响尚未处理的任务。本文测试与契约面向普通数据数组,不鼓励用带副作用的访问器、代理或定制迭代器作为输入。

独立文件:07.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const gate = Promise.withResolvers();
const input = ["A", , "C"];
const seen = [];
const batch = orderedMap(input, async (value, index) => {
  seen.push(index);
  if (index === 0) await gate.promise;
  return value === undefined ? "missing" : value;
}, 1);
input[2] = "changed";
input.push("D");
gate.resolve();
const result = await batch;
assert.deepEqual(result, ["A", "missing", "C"]);
assert.deepEqual(seen, [0, 1, 2]);
console.log("result=" + result.join(","));
console.log("input length=" + input.length + ", result length=" + result.length);

预期输出:

result=A,missing,C
input length=4, result length=3

如果业务要求深度不可变输入,应在业务边界选择合适的结构化复制或不可变数据策略,而不是让通用调度函数随意深拷贝。图片、句柄、数据库对象和循环引用都有不同约束。把快照深度写入文档,比让读者误以为复制数组就隔离了所有共享状态更可靠。

示例八:保留最先观察到的失败,不是下标最小的失败

保序只约束成功结果,不自动决定失败优先级。下面并发运行前三项,先让下标二失败,再让下标零失败,下标一成功。最终保留下标二的原因。若产品要求按照输入顺序选取最小失败下标,那是另一种契约,往往需要继续收集多个结果再决策,不能假装两种策略完全等价。

停止点同样必须讲清楚:只有某个 worker 执行 catch 并设置 stopped 后,才保证不再领取。若成功任务的续体先于失败续体执行,它可能先补进一个新任务。这不是超过并发上限,而是异步观察的正常边界。因此验收标准应写成首次捕获失败后停止领取,不能写成远端一发生失败就绝对零新增。

独立文件:08.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const gates = Array.from({ length: 3 }, () => Promise.withResolvers());
const started = [];
const earliest = new Error("index 2 observed first");
const lowIndex = new Error("index 0 observed later");
const batch = orderedMap([0, 1, 2, 3], (_value, index) => {
  started.push(index);
  return gates[index].promise;
}, 3);
const observed = batch.then(
  () => ({ ok: true }),
  reason => ({ ok: false, reason })
);
gates[2].reject(earliest);
await Promise.resolve();
assert.deepEqual(started, [0, 1, 2]);
gates[0].reject(lowIndex);
gates[1].resolve("done");
const outcome = await observed;
assert.equal(outcome.ok, false);
assert.equal(outcome.reason, earliest);
assert.deepEqual(started, [0, 1, 2]);
console.log("reason=" + outcome.reason.message);
console.log("index 3 never started");

预期输出:

reason=index 2 observed first
index 3 never started

收尾会带来一个诚实的代价:只要某个已经启动的 mapper 永远不结束,整个批次就永远不能完成拒绝。需要超时或中止时,业务操作应支持自己的截止时间或 AbortSignal,并把清理也纳入它返回的 Promise。调度器既不能凭空取消任意 Promise,也不应仅靠 Promise.race 就声称底层操作已经停止。

示例九:同步值、Promise、thenable 都归入同一条生命周期

mapper 不必总是声明成 async。await 可以接收普通值,也会采用 Promise 或 thenable 的最终状态。下面混合三种返回方式,再测试 then 属性访问器直接抛错的情况。它们都被同一个 worker 管理,无须用 instanceof Promise 分类;后者还会漏掉跨 realm Promise 与普通 thenable。

ECMAScript 的 Promise resolve 算法说明了读取 then 与采用 thenable 的处理路径。这不是允许 mapper 随意分叉后台工作的理由。代表真实工作的那条 Promise 链必须被返回;否则函数以为名额已释放,实际请求却还在继续,并发数字就只剩表面正确。

独立文件:09.mjs。

import assert from "node:assert/strict";

async function orderedMap(input, mapper, concurrency = 2) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive safe integer");
  }
  const values = Array.from(input);
  const output = new Array(values.length);
  let next = 0;
  let stopped = false;
  let firstReason;
  async function worker() {
    while (!stopped && next < values.length) {
      const index = next++;
      try {
        output[index] = await mapper(values[index], index);
      } catch (reason) {
        if (!stopped) {
          stopped = true;
          firstReason = reason;
        }
      }
    }
  }
  const count = Math.min(concurrency, values.length);
  await Promise.all(Array.from({ length: count }, () => worker()));
  if (stopped) throw firstReason;
  return output;
}

const result = await orderedMap([1, 2, 3], (value, index) => {
  if (index === 0) return value * 10;
  if (index === 1) return Promise.resolve(value * 10);
  return { then(resolve) { resolve(value * 10); } };
}, 2);
assert.deepEqual(result, [10, 20, 30]);
const boom = new Error("then getter failed");
const badThenable = Object.defineProperty({}, "then", {
  get() { throw boom; }
});
const started = [];
const batch = orderedMap([0, 1], (_value, index) => {
  started.push(index);
  return badThenable;
}, 1);
await assert.rejects(batch, error => error === boom);
assert.deepEqual(started, [0]);
assert.deepEqual(await orderedMap([1], () => undefined, 1), [undefined]);
console.log("mixed results=" + result.join(","));
console.log("thenable failure caught; undefined value accepted");

预期输出:

mixed results=10,20,30
thenable failure caught; undefined value accepted

异步并发也不等于 CPU 并行。mapper 在第一次 await 前执行的同步计算仍然占用当前线程;如果它做了长时间计算,其他 worker 不能靠这个函数同时获得 CPU。图片解码或大规模计算需要另评估 Worker Threads 等机制,而本例更适合有清晰返回 Promise 的有限 I/O 批处理。

把审查问题交给 AI,但把验收证据留在自己手里

如果让 AI 修改这份实现,可以直接要求它说明四个位置:索引在哪里唯一领取,mapper 在哪里真正启动,失败标志在哪里首次写入,以及所有在途工作在哪里被等待。然后要求它逐段运行九个测试,报告实际输出与退出状态。只有给出 happy path 的打印数组,不能证明失败收尾,也不能证明没有提前启动。

对比改动时尤其要警惕三类看似简化的写法:把 await mapper 改为提前构造所有 Promise;用结果 push 替换按索引赋值;把 stopped 与 firstReason 合并成一个真值判断。这些修改都可能减少代码行数,却悄悄改变已经承诺的行为。反过来,也别为了泛化而一次塞入重试、超时、取消、优先级与无限输入;每增加一个维度,都要给它独立的状态和验收案例。

这一实现需要保存输入快照与完整结果,空间随条目数增长;它不会解决海量输入的内存问题,也不会限住 mapper 内部自行并发的子请求。只有业务确实需要一次性交付完整有序数组,且每个 mapper 的 Promise 准确代表工作结束时,这个小工具才有清晰用途。对 AI 代码最有效的审查方式,是把自然语言需求改写成可控事件和可执行断言,让每一条承诺都能被反例挑战。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。