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?