Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading