node.js - nodejs异步模块导出

标签 node.js sequelize.js

我正在异步导出一个配置 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'表示您正在使用 awaitasync函数(“顶级等待”)并且不能在 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/

相关文章:

javascript - 防止 NodeJS 在开发/调试时缩小 JavaScript 代码

mysql - NodeJS 响应已在 MySQL 查询执行之前发送

javascript - Sequelize 搜索 API 无法按预期运行 expressJS

mysql - 在 sequelize 中关联两个表

node.js - EJS:<% 与 <%- --> 有什么区别

node.js - NodeJS Sequelize : Association with alias [alias] does not exist on [model]

linux - Ubuntu cron shebang 不工作

node.js - 如何使用sequelize ORM(即多线程)实现集群

javascript - 如何在不创建模拟的情况下测试数据库查询

sql - Sequelize - 在不同条件下对相同关联进行两次计数