在一个响应中合并响应数据
我有一个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, 
          }); 
     }); 
    }); 
我想在data。所以我怎么能做到这一点一个响应eventRes和eventBoostRes?
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个查询同步运行,是不是最佳的。你可以优化此使用的承诺和运行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) 
    }); 
}); 
在另一方面,这应该可以在查询级别处理。
回答:
您可以像这样将它们组合起来:
EventModal.eventSearch(eventReq, type, async function (eventRes) {     EventModal.getBoostEvents(eventReq, type, async function (eventBoostRes) { 
     res.json({ 
      status: true, 
      data: { 
       eventRes, 
       eventBoostRes 
      } 
     }); 
    }); 
}); 
以上是 在一个响应中合并响应数据 的全部内容, 来源链接: utcz.com/qa/263214.html
