【问题标题】:Module Exporting result of async fnasync fn 的模块导出结果
【发布时间】:2021-04-06 11:05:30
【问题描述】:

我使用的是标准节点 mysql 包并抽象出我的数据库连接。

const mysql = require('mysql');

const connection = mysql.createConnection({
    host: host,
    user: user,
    password: password,
    database: database
});

module.exports = connection;

我想使用 promises 并尝试使用包装好的 promise-mysql 包。

但是,我不清楚我是否仍然可以导出我的 connection 对象。

const mysql = require('promise-mysql');

const connection = await mysql.createConnection({
    host: host,
    user: user,
    password: password,
    database: database
});

module.exports = connection;

我必须将module.exports 包装在 IIFE 中吗?

【问题讨论】:

  • 您只能在异步函数中使用 await。无论如何,您可能没有理由导出连接。如果您想使用连接,只需在您的主脚本中执行此操作。否则,请创建一个处理这一切的类。
  • 我想抽象出数据库配置参数。这些将存储为 Env Vars。你会导出什么,只是一个用于参数的对象,并在每次需要时实例化一个连接?

标签: javascript mysql node.js promise


【解决方案1】:

您可以将导出设置为 createConnection 调用返回的 Promise。另请注意,在 ES6 中,您可以使用简写的属性名称以保持简洁和可读性:

const mysql = require('promise-mysql');
module.exports = mysql.createConnection({
    host,
    user,
    password,
    database
});

然后用户可以通过在 Promise 上调用.then 来使用它,例如:

const connectionProm = require('script.js');
connectionProm.then((connection) => {
  // do stuff with connection
});

如果您不喜欢在使用连接的任何地方都调用.then,另一种方法是使用依赖注入将连接作为参数向下传递,这样连接的.then 只需存在于脚本的入口点。

// index.js
connectionProm.then((connection) => {
  // do stuff with connection
  // pass it around as needed
});

// do NOT import or call connectionProm.then anywhere else

【讨论】:

  • 我使用的是async/await 而不是.then。但是导出承诺就成功了。 const connection = await require('script') 工作
猜你喜欢
  • 2018-09-30
  • 2022-08-16
  • 2017-05-07
  • 2018-08-12
  • 1970-01-01
  • 2017-10-30
  • 2020-05-03
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多