【发布时间】:2021-10-12 02:36:19
【问题描述】:
我想知道配置模块导出的最佳方法是什么。下面示例中的“async.function”可以是 FS 或 HTTP 请求,为了示例而简化:
这是示例代码(asynmodule.js):
var foo = "bar"
async.function(function(response) {
foo = "foobar";
// module.exports = foo; // having the export here breaks the app: foo is always undefined.
});
// having the export here results in working code, but without the variable being set.
module.exports = foo;
如何仅在执行异步回调后导出模块?
编辑 关于我的实际用例的快速说明:我正在编写一个模块来在 fs.exists() 回调中配置 nconf (https://github.com/flatiron/nconf)(即,它将解析配置文件并设置 nconf)。
【问题讨论】:
-
一直在玩我的实际用例,如果使用不存在的文件调用 nconf.file(),则 nconf 加载正常,所以现在我不需要解决方案。但我仍然对这种方法感兴趣。
-
我有同样的问题,我想导出一个承诺,
require异步加载依赖项。我认为使用 babel 格式化程序是可能的。但是,我认为这不是一个好的解决方案。 :(
标签: node.js asynchronous