Search code examples
javascriptconstantses6-promise

how to assign a top-level const from a promise when top-level await is not available


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.


Solution

  • 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.