Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
waiting for database to connect before exporting module functions to controller

I am getting the error below:

Service.getUsers is not a function

I recently changed my code to include this functionality:

async function connectToDatabase(secret) {
  try {
      const secretValue = await getSecretPromise(secret)

      const { host, port, username, password, dbname } = JSON.parse(secretValue);

      con = mysql.createConnection({
          host: host,
          port: port,
          user: username,
          password: password,
          database: dbname
      });
      con.connect(function(err) {
        if (err) throw err;
        console.log("Connected to database!");
      });
  } catch (error) {
      console.error(error)
  }
}

connectToDatabase(secretName).then(function() {
  module.exports = {
    createUser,
    getUsers,
    patchUser,
    loginUser,
    updateCallForward,
    getEmail,
    getCallForwardingNumber,
  };
});;

Basically, it will only export the functions to the controller if the database is connected and the value of con is initialized (this ensures that the value of con is not undefined which has been troubling me). However, when I do this, it messes with the controller js and I get the error above.

var accountService = require('./account.service');
router.get('/get-users', getUsers);

async function getUsers(req, res, next) {

    accountService.getUsers().then(function(val) {
        res.json(val)
    });
}

I believe this is because of the waiting that is employed in the service.js. Is there anyway I can make the controller wait for the functions to get initialized through the export?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!