In my node.js application, I call a sequelize query, and inside its .then() I call another sequelize query. I want the result of the second query to be appended to the first query so that it can be returned as a JSON with a JSON Array inside it. how can this be done?
{
result1,
result2[
...
]
}
You can append two result sets into an array, roughly as follows:
let myResult = []; // container for two results
SomeModel.findAll({
where: {'someField' : { [Op.like]: '%b%' }}
}).then(firstResultSet => {
myResult.push(firstResultSet);
SomeOtherModel.findAll(
{where: {'someField' : { [Op.like]: '%a%' }
}).then(secondResultSet=> {
myResult.push(secondResultSet);
result.send(myResult);
next();
});
})
Using Promise.all
and the ES6 array spread will give you a nice clean implementation. Note that if your arrays are of different types you'll find it challenging to reliably iterate over your final result.
const Some = SomeModel.findAll({ where: {'someField': { [Op.like]: '%b%' }} });
const Other = OtherModel.findAll({ where: {'someField': { [Op.like]: '%a%' }} });
Promise.all([Some, Other]).then([some, other] => [...some, ...other]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.