首页 > 解决方案 > 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');

但我收到错误消息说意外的保留字“等待”

标签: node.jssequelize.js

解决方案


您的配置模块中有错字: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();

推荐阅读