我一直在阅读有关如何不阻止 Node 的事件循环的内容。避免阻塞的一种方法是使用分区。
我试图在我的代码中使用分区循环,但我似乎无法等待我的循环。这是我的代码的简化版本:
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1;
// all sorts of async operations here that use async-await
if (report.someValue < 1000) {
await setImmediate(runLoop);
}
};
await runLoop();
console.log('Report is', report);
Run Code Online (Sandbox Code Playgroud)
这会返回“Report is { someValue: 1 }”,但我希望 someValue 为 1000。
我猜 setImmediate 不会返回承诺,所以我尝试承诺它:
const setImmediatePromise = util.promisify(setImmediate);
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1; …Run Code Online (Sandbox Code Playgroud)