javascript - Node.js: How to return a rejcted promise without getting UnhandledPromiseRejectionWarning -
i have function in module uses request-promise-native module query couchdb database:
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 function uses first one:
router.get('/checkemailexistence', (req, res) => { couchdb.userbyemail(req.param('email')) .then((userarray) => { res.status(200).end(userarray.length > 0); // returns 'true' if @ least 1 user found }) .catch((e) => { winston.log('error', e.message); res.status(500).end(e.message); });
in case there no database connection, promise request-promise-native module rejected. want catch rejection in second function , return internal server error caller. forward rejection request-promise-native module catch in first function , return new rejected promise.
unfortunately warning have unhandled promise rejection. how can solve issue?
edit
i've seen used wrong codepath testing. coding above works without producing warning. sorry confusion.
this happen because promise always has return something.
you can fix 'issue' return null
router.get('/checkemailexistence', (req, res) => { couchdb.userbyemail(req.param('email')) .then((userarray) => { res.status(200).end(userarray.length > 0); // returns 'true' if @ least 1 user found return null }) .catch((e) => { winston.log('error', e.message); res.status(500).end(e.message); return null }); });
Comments
Post a Comment