[英]How to wait for promise before exporting a variable?
How do I export a value only after the promise is completed?如何仅在 promise 完成后导出值? Suppose I have something like this in a secrets.js
file:假设我在secrets.js
文件中有这样的内容:
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
?如何在导出secretsData
之前等待 promise 完成?
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).我想避免将异步处理引入到导入secrets.js
文件的代码的所有其他区域(这可能会冒泡到它们的父函数等等)。 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?实现依赖于要完成的 promise 的秘密(或某种形式的配置)的最简单/惯用/最干净的方法是什么?
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您可以参考这里了解更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.