【发布时间】:2020-09-21 05:24:07
【问题描述】:
我正在尝试捕获 mongoose/mongodb 的连接成功状态。 这个想法很简单,当我启动应用程序时,如果连接失败,我需要记录一个警报。 我不知道为什么,一旦我连接 - 或者一旦连接失败 - 该函数不会返回我告诉它返回的内容。
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;
我只是调用它并尝试显示结果。 但无论数据库状态如何,都会忽略 .then 或 .catch 中的 return 语句 Server.js:
const connectMe = require('./db-actions/db-connect');
const myResult = connectMe();
myResult.then(x => console.log(x));
如果 mongodb 启动,我会得到这个:
数据库连接成功 我为什么要退货????
如果 mongodb 出现故障,我会得到这个:
无法连接到 mongodb 实例。错误:MongooseServerSelectionError:连接 ECONNREFUSED 127.0.0.1:30000 我为什么要退货????
Console.log 有效,但返回无效。 知道为什么吗?
【问题讨论】:
标签: node.js mongodb mongoose async-await