[英]Node.js: How to return a rejcted promise without getting UnhandledPromiseRejectionWarning
I have a function in a module that uses the request-promise-native module to query a couchdb database: 我在一个模块中有一个函数,该模块使用request-promise-native模块来查询ouchdb数据库:
userByEmail: (email) => {
const options = {
url: `${config.couchdb.url}/medlog/_design/user/_view/by_email_or_userid?key="${email}"`,
json: true,
};
return rp.get(options)
.then(users => users.rows.map(row => row.value))
.catch(reason => Promise.reject(new Error('test')));
}
A second module contains a function that uses the first one: 第二个模块包含使用第一个模块的函数:
router.get('/checkEmailExistence', (req, res) => {
couchdb.userByEmail(req.param('email'))
.then((userArray) => {
res.status(200).end(userArray.length > 0); // returns 'true' if at least one user found
})
.catch((e) => {
winston.log('error', e.message);
res.status(500).end(e.message);
});
In the case that there is no database connection, the promise from the request-promise-native module is rejected. 在没有数据库连接的情况下,来自请求-承诺-本机模块的承诺将被拒绝。 What I want is to catch that rejection in the second function and return an internal server error to the caller. 我想要的是在第二个函数中捕获该拒绝,然后将内部服务器错误返回给调用方。 To forward the rejection from the request-promise-native module I catch it in the first function and return a new rejected promise. 为了转发来自request-promise-native模块的拒绝,我将其捕获到第一个函数中并返回一个新的被拒绝的promise。
Unfortunately I always get the warning that I have an unhandled promise rejection. 不幸的是,我总是得到警告,说我有未处理的承诺被拒绝。 How can I solve that issue? 我该如何解决这个问题?
EDIT 编辑
I've just seen that I used the wrong codepath for testing. 我刚刚看到我使用了错误的代码路径进行测试。 So the coding above works without producing the warning. 因此,上面的编码可以正常工作而不会产生警告。 Sorry for the confusion. 对困惑感到抱歉。
This happen because a Promise always has to return something. 发生这种情况是因为Promise 总是必须返回某些东西。
You can fix this 'issue' with a return null 您可以使用返回null修复此“问题”
router.get('/checkEmailExistence', (req, res) => {
couchdb.userByEmail(req.param('email'))
.then((userArray) => {
res.status(200).end(userArray.length > 0); // returns 'true' if at least one user found
return null
})
.catch((e) => {
winston.log('error', e.message);
res.status(500).end(e.message);
return null
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.