我对 NodeJS 很陌生。我正在尝试创建一个与我的 mongoDB Atlas 数据库连接的简单服务器,但是当我运行我的服务器时,我收到此错误:
UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这
错误是通过抛出异步函数内部而产生的
没有 catch 块,或者拒绝一个不符合的承诺
用 .catch() 处理。 (拒绝 ID:1)(节点:8825)[DEP0018]
DeprecationWarning:未处理的承诺拒绝已被弃用。在
未来,承诺拒绝未处理的将终止
具有非零退出代码的 Node.js 进程。
根据我搜索的内容,这似乎是一个常见问题,我添加了 try/catch 但它仍然不起作用。
'use strict';
//const AWS = require('aws-sdk');
const express = require('express');
const mongoose = require('mongoose');
const uuidv4 = require('uuid/v4');
//exports.handler = (event, context, callback) => {
mongoose.connect(
'mongodb+srv://xxxx:[email protected] /cdn-cgi/l/email-protection/test?retryWrites=true',
{
useNewUrlParser: true
}
),
() => {
try {
//something
} catch (error) {
console.error(error);
}
};
const connection = mongoose.connection;
connection.once('open', () => {
console.log('???? Connection to DB was succesful');
});
const app = express();
app.listen({ port: 4800 }, () =>
console.log(`???? Server ready at http://localhost:4800`)
);
Mongoose connect 返回承诺,并且很可能在尝试连接时出现错误:我建议使用异步函数来处理数据库连接。这是我目前使用的。
const config = require('config').db; // Your DB configuration
const combineDbURI = () => {
return `${config.base}${config.host}:${config.port}/${config.name}`;
};
// Connecting to the database
const connect = async function () {
const uri = combineDbURI(); // Will return DB URI
console.log(`Connecting to DB - uri: ${uri}`);
return mongoose.connect(uri, {useNewUrlParser: true});
};
然后使用await 在异步函数中调用它:
(async () => {
try {
const connected = await connect();
} catch(e) {
console.log('Error happend while connecting to the DB: ', e.message)
}
})();
或者您可以使用 Promise API 进行调用而无需等待:
connect().then(() => {
console.log('handle success here');
}).catch((e) => {
console.log('handle error here: ', e.message)
})
此外,在使用回调时使用 try catch 没有意义,当你没有 Promise 时,你应该使用错误回调来捕获错误。
所以回答你的问题(正如其他人在评论中提到的):
当 connect 函数返回一个 Promise 时,您应该使用 catch 回调来捕获 Promise 拒绝。否则,它将抛出 Unhandled Promise Rejection。
我希望这个能帮上忙。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)