I am writing a node API and want to save the results of a Sequelize query in a variable as a plain JavaScript object outside of the findAll
block. I have something that works, but not as well as I would like. Here is what I have:
router.get('/', (req, res, next) => {
models.User.findAll({
attributes: ['id', 'name'],
raw: true
}).then(function (results) {
console.log(results); // Plain JavaScript object, which is good
// Do logic on results
//Return results
res.status(200).json({
results
});
});
});
But I really don't want to keep all my logic within the then()
block, especially since I might want to do some other queries before or after this one. I really want something like (if this was a thing):
router.get('/', (req, res, next) => {
var users = models.User.findAll({
attributes: ['id', 'name'],
raw: true
}).then(function (results) {
});
});
// Do logic on results
// return results
res.status(200).json({
results
});
});
I tried to save the sequelize query in a function below the router.get()
call and return the results while they were a JavaScript object, but that didn't work. I am very new to JavaScript, so I appreciate the advice.
Well, if you don't want your logic code in the then
block, you might as well use async-await
:
router.get('/', async (req, res, next) => {
var results = await models.User.findAll({
attributes: ['id', 'name'],
raw: true
});
// you've result variable available here, use it.
// Do logic on results
// return results
res.status(200).json({
results
});
});
now you don't have to write the code in then
block, you can just use the variable results
in the function directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With