Node.js:如何在不获取UnhandledPromiseRejectionWarning的情况下返回被拒绝的承诺

我有一个使用request-promise-native模块查询couchdb数据库的模块中的函数:

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

第二个模块包含一个使用第一个模块的函数:

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

在没有数据库连接的情况下,拒绝来自request-promise-native模块的许诺。 我想要的是在第二个函数中捕获拒绝,并向调用者返回内部服务器错误。 为了拒绝来自request-promise-native模块的拒绝,我在第一个函数中捕获它,并返回一个新的被拒绝的承诺。

不幸的是,我总是得到警告,我有一个未经处理的承诺拒绝。 我该如何解决这个问题?


编辑

我刚刚看到我使用了错误的代码path进行testing。 所以上面的代码不会产生警告。 对困惑感到抱歉。

这是因为一个Promise 总是要返回一些东西。

你可以通过返回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 }); });