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.