0
votes

I'm trying to capture the connection success state for mongoose/mongodb. The idea is simply that, when I start the app, if the connection fails, I need an alert recorded. I can't figure out why, once I connect - or once the connection fails - the function does not return what I tell it to return.

import { DBURL } from '../parameters/environment';

const mongoose = require('mongoose');
const chalk = require('chalk');

const connected = chalk.bold.cyan;
const error = chalk.bold.yellow;

const connectMe = async () => {
  await mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch((reason) => {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    });
  return 'Why am I returning this????';
};

module.exports = connectMe;

I simply call it and try to display the result. But regardless of the DB state, the return statement in .then or .catch is ignored Server.js:

const connectMe = require('./db-actions/db-connect');

const myResult = connectMe();
myResult.then(x => console.log(x));

If mongodb is up, I get this:

DB connection successful Why am I returning this????

If mongodb is down, I get this:

Unable to connect to the mongodb instance. Error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:30000 Why am I returning this????

Console.log works, but the return does not. Any idea why?

1

1 Answers

0
votes

Why it seems return is not working:
You are combining both async/await and .then/.catch, you should choose one of the two. Also, the return keyword is not properly placed within connectMe the function.

The fix:
Since, you are expecting the connectMe function to return a promise so you can attach a .then like this:

myResult.then(x => console.log(x));

You can just go with a .then/.catch in the connectMe function and the return statement should be on mongoose.connect, that's the promise the outside world(i.e outside the function) needs to interact with. Code:

const connectMe = () => {
  return mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch ((reason) =>  {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    })
};