async fn 的模块导出结果 [英] Module Exporting result of async fn

查看:36
本文介绍了async fn 的模块导出结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用标准节点 mysql 包并抽象出我的数据库连接.

I was using the standard node mysql package and abstracted away my db connections as such.

const mysql = require('mysql');

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

module.exports = connection;

我想使用 promises 并且正在尝试使用包装的 promise-mysql 包.

I want to use promises and am trying to use the wrappered promise-mysql package.

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

However, I'm unclear as to if I can still export my connection object.

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

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

module.exports = connection;

我是否必须将 module.exports 包装在 IIFE 或其他东西中?

Do I have to wrap the module.exports in an IIFE or something?

推荐答案

您可以使导出为 createConnection 调用返回的 Promise.另请注意,在 ES6 中,为了简洁和可读性,您可以使用速记属性名称:

You can make the export be the Promise returned by the createConnection call. Also note that in ES6, you can use shorthand property names for conciseness and readability:

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

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

Then users can use it by calling .then on the Promise, eg:

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

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

If you don't like having to call .then everywhere the connection is being used, an alternative would be to use dependency injection to pass the connection down as arguments, so that the connection's .then only has to exist in the script's entry point.

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

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

这篇关于async fn 的模块导出结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆