← 中文资源

简体中文版本

分块处理时让出事件循环

把大批计算切成小块、每块之间 await 一个 setTimeout 宏任务,定时器与 I/O 才有机会插入;await Promise.resolve() 只让出微任务队列。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

chunk total 14
timer interleaved between chunks
chunk total 91
chunk total 204
final 204

实现说明

整个示例围绕函数 yieldToEventLoop、sumSquares组织。 迭代是嵌套的:for (let i = 0; i < values.length; i += chunkSize) 框定这一趟,for (const value of values.slice(i, i + chunkSize)) 做逐项处理。异步流被 await 线性化,失败处理保持局部。

使用要点

  • 演示输出是带标签的(chunk total、timer interleaved between chunks、final),每个操作都会留下自己的一行标注。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 yieldToEventLoop、sumSquares。

签名一览:const yieldToEventLoop = ()

核心语句

const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve));
sumSquares([1, 2, 3, 4, 5, 6, 7, 8], 3).then((total) => {
  console.log("final", total);
});
await yieldToEventLoop();

代码示例

const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve));

async function sumSquares(values, chunkSize) {
  let total = 0;
  for (let i = 0; i < values.length; i += chunkSize) {
    for (const value of values.slice(i, i + chunkSize)) {
      total += value * value;
    }
    console.log("chunk total", total);
    // Macrotask yield: pending timers and I/O run before the next chunk.
    // (await Promise.resolve() would only drain the microtask queue.)
    await yieldToEventLoop();
  }
  return total;
}

// A timer scheduled before the work proves the loop got control back
setTimeout(() => console.log("timer interleaved between chunks"), 0);

sumSquares([1, 2, 3, 4, 5, 6, 7, 8], 3).then((total) => {
  console.log("final", total);
});