I know blocking the event loop is bad and the consequences of that. But even the native fs module provides some sync functions for some purposes, for example, CLIs using fs.readFileSync
.
I'd like to convert the following async-await code to blocking code.
let value = undefined;
function setup() {
return new Promise((resolve) => {
setTimeout(() => {
value = "**value**";
resolve();
});
});
}
// need to convert below function to blocking
async function getValue() {
await setup();
return value;
}
console.log(await getValue()); // top level await OK
Assuming it is blocking, we can then call it like
getValue(); // without await or .then
I tried it like this. But it is not working.
function getValue() {
setup();
while (!value) {
// wait until we get value
}
return value;
}
console.log(getValue())
How can I achieve this?
(The fs.readFileSync
is blocking. Is there any way we can use the technique used by readFileSync)
Edit
Related thread: Convert asynchronous/callback method to blocking/synchronous method