最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

UnhandledPromiseRejectionWarning即使代码已经尝试异步内 AWAIT抓

运维笔记admin8浏览0评论

UnhandledPromiseRejectionWarning即使代码已经尝试/异步内/ AWAIT抓

UnhandledPromiseRejectionWarning即使代码已经尝试/异步内/ AWAIT抓

我知道这可能看起来像是其他问题重复,但我看着每一个建议SO问题,我可以张贴在此之前找到的,我正在寻找在这种特定情况下帮助,因为没有其他的答案都为我工作。

我有一个REST API使用的是正在初始化一个MongoDB的连接节点/快速应用。第一步是连接到MongoDB实例。如果初始连接失败,因为预期它会抛出一个错误。我使用异步/等待里面的它处理的是一个try / catch块。我到处都看过说,这应该足以捕捉这些异步/ AWAIT承诺拒绝,但我一直没有身在何处,我扔在一个.catch()或try / catch语句为我的代码(如在其他SO帖子建议得到关于UnhandledPromiseRejection错误)。

在这个环节,比如,我有相当多的是在错误处理部分中描述的同样的事情,但问题依然存在。

这里的错误(我知道是什么原因造成的错误本身 - 我有MongoDB的服务,现在停止了 - 但我试图修复未处理的承诺废品):

(node:15633) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:15633) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:13802) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] at Pool.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/topologies/server.js:562:11) at Pool.emit (events.js:189:13) at Connection.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/pool.js:316:12) at Object.onceWrapper (events.js:277:13) at Connection.emit (events.js:189:13) at Socket.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/connection.js:245:50) at Object.onceWrapper (events.js:277:13) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19)

这里是我的代码:

exports.mongoConnect = async (dbName, archiveDbName, userName, password) => {

    // Auth params
    const user = encodeURIComponent(userName);
    const pass = encodeURIComponent(password);
    const authMechanism = 'DEFAULT';

    // Connection URL
    const url = `mongodb://${user}:${pass}@localhost:27017?authMechanism=${authMechanism}&authSource=admin`;
    let client;

    try {
        // Use connect method to connect to the Server
        client = await MongoClient.connect(url, { useNewUrlParser: true, poolSize: 10, autoReconnect: true, reconnectTries: 6, reconnectInterval: 10000 }).catch((e) => { console.error(e) });

        db = client.db(dbName);
        archiveDb = client.db(archiveDbName);

        console.log(`Succesfully connected to the MongoDb instance at URL: mongodb://localhost:27017/ with username: "` + client.s.options.user + `"`);
        console.log(`Succesfully created a MongoDb database instance for database: "` + db.databaseName + `" at URL: mongodb://localhost:27017/`);
        console.log(`Succesfully created a MongoDb database instance for database: "` + archiveDb.databaseName + `" at URL: mongodb://localhost:27017/`);
    } catch (err) {
        console.log(`Error connecting to the MongoDb database at URL: mongodb://localhost:27017/` + dbName);
    }
}

正从这样的app.js称为:

mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'myUser', 'myPassword');

我甚至试图把在try / catch块线,或者加入承诺式.catch()到它的结束,没有变化。

我似乎无法弄清楚它为什么还在抱怨不处理的承诺拒绝。

编辑:

这里是整个app.js文件:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var cors = require('cors');
var app = express();

const MongoClient = require('mongodb').MongoClient;
// This is where the mongo connection happens
var mongoUtil = require( './services/mongoUtil' );
var bluebird = require('bluebird');

const jwt = require('./helpers/jwt');

var api = require('./routes/api.route')

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev'));
app.use(express.json()); 
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', api);

// use JWT auth to secure the api
app.use(jwt());

app.use('/users', require('./users/users.controller'));

MongoClient.Promise = bluebird

mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;`
回答如下:

我测试你的代码,它工作正常,你可以在下面的屏幕截图看到。我觉得问题在于无论是调用mongoConnect()

发布评论

评论列表(0)

  1. 暂无评论