Module Exporting result of async fn

Viewed 745

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;

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

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;

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

1 Answers

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
});

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

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

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
Related