Reputation: 1492
I have a NodeJS server that takes data from two different API's, and then I want to combine the result from both in one JSON response. Here I am sending you the code:
EventModal.eventSearch(eventReq, type, async function (eventRes) {
EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) {
res.json({
status: true,
data: eventRes,
eventBoostRes: eventBoostRes,
});
});
});
I want eventRes
and eventBoostRes
in one response in data
.So how can I achieve that ?
eventRes
and eventBoostRes
are query result.
Thanks in advance.
Upvotes: 2
Views: 3370
Reputation: 5578
Question not very clear.
However, it sounds like you are getting 2 arrays and you want to return a single array in the response. Quick ( and dirty ) way to do this is use array.concat( anotherArray )
function:
EventModal.eventSearch(eventReq, type, async function (eventRes) {
EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) {
res.json({
status: true,
data: eventRes.concat( eventBoostRes )
});
});
});
However, this will cause 2 queries to run in sync and is not optimal. You could optimise this to use promises and run 2 queries in parallel:
Promise.all([ // this will run in parallel
EventModal.eventSearch(eventReq, type),
EventModal.getBoostEvents( eventReq, type )
]).then( function onSuccess([ eventRes, eventBoostRes ]) {
res.json({
status: true,
data: eventRes.concat( eventBoostRes )
});
});
On the other hand; this should probably be handled at the query level.
Upvotes: 1
Reputation: 6831
You can combine them like this:
EventModal.eventSearch(eventReq, type, async function (eventRes) {
EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) {
res.json({
status: true,
data: {
eventRes,
eventBoostRes
}
});
});
});
Upvotes: 2