I'm trying to assign a const at the top-level, where the value needs to come from an asynchronous function. However the version of nodejs on the production server I am using is not new enough to support await, so I can't do something like this:
const value = await f(x)
I can't declare the variable inside something like then because it isn't scoped at the top level, so something like this won't work:
f(x).then(val=>{const value=val}) // no top-level const value afterwards
How can I initialize the const properly in this environment?
If it helps, for this particular case the function actually does return synchronously for the particular value I am passing it, but since it's defined as async and sometimes returns asynchronously it's actually returning a Promise all the time.
As a (horrible) workaround, I considered simply assigning the const to the Promise and then extract the value whenever I needed it using .then(). However, despite the Promise being resolved this seems to always cause the value to be extracted asychronously, which means it won't work as when I need the value I need it right at that point and not after the current function completes or whenever.
You need to define you var with "let" instead of const, then assign the value in the "then".
let value;
f(x).then(val => value = val)
Maybe you have a better way to do this, but with the contexte we have, I would do it this way.
You'll have to move all code that needs the value of that const inside a function. Either move it in a (large) then callback, or create an async function wrapper.
So let's say your code now looks like this:
async function f(x) {
// ....
return //...
}
function g(value) {
// something
}
const value = await f(x);
// ...
g(value);
// ...
console.log(value);
// ...
Then change that to:
(async function main() {
async function f(x) {
// ....
return // ...
}
function g(value) {
// something
}
const value = await f(x);
// ...
g(value);
// ...
console.log(value);
// ...
})(); // Execute main
OK, it is not absolutely necessary to move everything in it, but this just shows how you can solve your problem.