Reputation: 357
The Promise returns undefined
when trying to log it in routes.js
, however works fine when logging in queries.js
. How should i change the promise to correctly return a response to routes.js
?
in queries.js
:
const rsClient = require('./client.js');
const query = {
one: 'SELECT * FROM my.db'
}
module.exports = {
rsProdRecs: (req, res) => {
rsClient.query(query.one)
.then(res => {
return res;
})
.catch(err => console.log(err));
}
};
in routes.js
var express = require('express');
var router = express.Router();
var queries = require('../queries');
router.get('/', function(req, res, next) {
const data = queries.rsProdRecs();
console.log(data)
res.send(data);
});
module.exports = router;
Upvotes: 0
Views: 776
Reputation: 6063
There's a few issues with your code. The first issue has already been pointed out by other users, you need to return the promise from rsProdRecs
. The then
and catch
blocks are also problematic as well as how you are consuming the method in your route, as described in the code below:
module.exports = {
rsProdRecs: (req, res) => {
return rsClient.query(query.one);
// This is redundant, you're not transforming res in any way so this can be omitted.
// .then(res => {
// return res;
// })
// This will cause the promise to return 'undefined' if rsClient.query(...) rejects,
// instead error handling should be done in the calling function.
// .catch(err => console.log(err));
}
};
And you can refactor your route to properly consume your Promise
returning method:
router.get('/', function (req, res, next) {
// We cannot consume the "data" directly, we must wait for the promise to resolve.
queries.rsProdRecs()
.then((data) => {
console.log(data);
res.send(data);
})
.catch((err) => {
console.log(err);
res.status(500); // insert correct error response here
});
});
Or use async/await
since you are already using ES6 funcionality:
router.get('/', async function (req, res, next) {
try {
const data = await queries.rsProdRecs();
console.log(data);
res.send(data);
} catch (e) {
console.log(err);
res.status(500);
}
});
Upvotes: 2
Reputation: 413
Did you try add return
statement?
rsProdRecs: (req, res) => {
return rsClient.query(query.one)
.then(res => {
return res;
})
.catch(err => console.log(err));
}
Upvotes: 2