我有一个NodeJS服务器,该服务器从两个不同的API接收数据,然后我想将两者的结果合并到一个JSON响应中。在这里,我向您发送代码:
EventModal.eventSearch(eventReq, type, async function (eventRes) {
EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) {
res.json({
status: true,
data: eventRes,
eventBoostRes: eventBoostRes,
});
});
});
我想要eventRes
并eventBoostRes
在一个回应中data
。那么我该如何实现呢?
eventRes
和eventBoostRes
是查询结果。
提前致谢。
问题不是很清楚。
但是,听起来您要获得2个数组,并且您想在响应中返回一个数组。快速(又脏)的方法是使用array.concat( anotherArray )
功能:
EventModal.eventSearch(eventReq, type, async function (eventRes) {
EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) {
res.json({
status: true,
data: eventRes.concat( eventBoostRes )
});
});
});
但是,这将导致2个查询同步运行,而不是最佳的。您可以优化此方法以使用promise并并行运行2个查询:
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 )
});
});
另一方面; 这可能应该在查询级别进行处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句