实现说明
整个示例围绕函数 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);
});