简体   繁体   中英

How to wait for promise before exporting a variable?

How do I export a value only after the promise is completed? Suppose I have something like this in a secrets.js file:

var secretsData;

(async function () {
  secretsData = await getSecret(); // makes some async API call to AWS Secrets Manager
})();

module.exports = secretsData;

How can I wait for the promise to complete before exporting secretsData ?

I want to avoid having to introduce async handling to all the other areas of my code that imports the secrets.js file (which could possibly bubble up to their parent functions and so on). In my opinion, it's just much simpler to deal with if I can just import and use the secrets with the assumption that it is already populated:

var secretsData = require("../secrets");
... do something with secretsData.url ...
... do something with secretsData.db.password ...

It feels like its a simple problem but I can't seem to find any solution to this. Most of the articles I've read seems to just suggest the only solution is to make everything that relies on the secrets to become async as well, but this feels like such a complicated solution for something so simple (especially when there are many places that depend on the secrets).

What is the simplest/idiomatic/cleanest way of implementing secrets (or some form of config) that depend on a promise to be completed?

Try

module.exports = await secretsData;

you can refer to here for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM