JavaScript call async function before exporting a JSON object

First of all, this is NOT a duplicate of this question. The person asking here is using axios and was able to do it with interceptors, but I'm exporting a simple a JSON object that (obviously) doesn't have this feature.

My use case is to have a file that exports a config JSON object. This way, other files can import this file and access the app config.

Here is how it works:

  1. I have an asynchronous function that gives me a config value. Let's call this function getSomeConfig(). It also has a callback form if that helps. (This is a mongoose query.)
  2. I have a config JSON object that I export at the end of the file.
  3. getSomeConfig() is supposed to set the value of a key in the JSON object. But, since getSomeConfig() is asynchronous, this isn't straightforward.

The solution I've found so far is to use top-level await. However, this isn't yet ratified by ECMAScript, so I would prefer not using it.

The second answer to the question in the beginning mentioned that I could export an async function and call that to get the config. Unfortunately, other files that import this config file aren't necessarily asynchronous, so this way of doing also wouldn't work for me.

Read more here:

Content Attribution

This content was originally published by Gabor Szita at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: