I've been reading about how to not block Node's event loop. One way to avoid blocking is to use partitioning.
I'm trying to use a partitioned loop in my code, but I cannot seem to await for my loop. Here's a simplified version of my code:
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);
This returns "Report is { someValue: 1 }", but I'd want someValue to be 1000.
I'm guessing setImmediate doesn't return a promise, so I've tried promisifying it:
const setImmediatePromise = util.promisify(setImmediate);
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 setImmediatePromise(runLoop);
}
};
await runLoop();
console.log('Report is', report);
But this also returns "Report is { someValue: 1 }".
So, how can I await for this recursive setImmediate "loop" so that I console.log report only after the entire recursion cycle is finished?