我正在异步导出一个配置 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();
关于node.js - nodejs异步模块导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66902174/