【问题标题】:mongoose async await, unable to capture connection state猫鼬异步等待,无法捕获连接状态
【发布时间】: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


    【解决方案1】:

    为什么 return 似乎不起作用:
    您正在组合async/await.then/.catch,您应该选择两者之一。此外,return 关键字未正确放置在 connectMe 函数中。

    修复:
    因为,您期望 connectMe 函数返回一个承诺,因此您可以像这样附加 .then

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

    您可以在connectMe 函数中使用.then/.catch,并且return 语句应该在mongoose.connect 上,这是外部世界(即函数外部)需要与之交互的承诺。代码:

    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';
        })
    };
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2019-05-10
      • 2020-10-16
      • 2020-08-01
      • 2018-04-13
      • 2019-02-15
      • 2018-06-11
      • 2019-12-12
      • 2018-08-09
      相关资源
      最近更新 更多