TemporaryFix
TemporaryFix

Reputation: 2186

Express await database connection

I am following a related post here

I am struggling with awaiting the module import from my express application.

I understand that to use await, it must be wrapped in an async function. However I can't wrap my entire node program in an async function because it will exit without doing anything useful.

How can I properly await the database connection?

node/express:

require('dotenv').config();
var express = require('express');
var loginRouter = require('./routes/login/login');
var app = express();

async() => {
    const { client } = await require('./db/db');
    app.use('/login', loginRouter);
    app.set('port', process.env.PORT || 3000);
    app.listen(app.get('port'));
    console.log('Server listening on port ' + app.get('port'));
}

db module:

const { Client } = require('pg');

module.exports = (async() => {
    const client = new Client();
    await client.connect();
    return { client };
})();

Upvotes: 2

Views: 977

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

One option would be to export a Promise that resolves to a connected client. Then, when you import it, call .then on the imported Promise to get to the connected client:

const { Client } = require('pg');

const client = new Client();
module.exports = {
  clientProm: client.connect().then(() => client)
};

And:

const { clientProm } = require('./db/db');
clientProm.then((client) => {
  // do stuff with connected client
});

Upvotes: 1

Related Questions