node.js - nodejs异步模块导出
问题描述
我正在异步导出一个配置 js 对象。如何在另一个模块中异步使用导出的对象?
module.export = (async function(){
connConf = await getDbConnectionConfiguration('administration_db');
const config = {
development: {
username: connConf.user,
password: connConf.password,
host: connConf.host,
database: connConf.database}
};
return config;
})();
然后我将上面的模块导入到另一个对象中,如下所示,
const configs = await require('../config');
但我收到错误消息说意外的保留字“等待”
解决方案
您的配置模块中有错字:module.export
应该是module.exports
.
此外,您会立即在导出时调用您的函数并返回待处理的 Promise。最好删除最后一个括号并返回函数本身:
//fixed typo V
module.exports = (async function(){
connConf = await getDbConnectionConfiguration('administration_db');
const config = {
development: {
username: connConf.user,
password: connConf.password,
host: connConf.host,
database: connConf.database
}
};
return config;
}); // <-- parenthesis removed here
Unexpected reserved word 'await'
意味着您正在使用await
外部async
函数(“顶级等待”)并且无法在 CommonJS ( .js
) 模块中完成。
一种解决方法是将代码包装在异步函数中并调用它:
const configsModule = require('./config'); // <-- your imported async function
async function init() {
const configs = await configsModule();
// all you code should be here now
console.log(configs);
}
// call init
init();
如果您的 Node 是 14 或更高版本并且您切换到 ES 模块(),则另一种方法是使用顶级等待.mjs
:
// app.mjs
import configsModule from '../config';
const configs = await configsModule();
推荐阅读
- powershell - 如何在每次运行时将所有数据存储在缓存中,并在下次运行时检查它是否已经存在于缓存中以获得更快的运行时间?
- javascript - 将 JavaScript var 传回 Flask 并重新加载 ajax
- bash - 尝试使用 WSL 执行脚本,但在 `bash` 命令之后它不执行任何操作
- sql - 如何在 JSON 数组中循环子列表
- gnuplot - 如何通过字符串定义颜色名称以在 linecolor lc 中使用,不工作 gnuplot
- python - Python根据输入执行函数中的某些步骤
- java - spring boot - 在 oracle 数据库上回滚
- python - 从异步函数监视 multiprocessing.pool.Pool 对象
- xamarin - 滚动页面时隐藏 TopTabs
- c# - 为什么 PreviewMouseUp 在 PreviewMouseDown 之前触发并快速拖动