最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在一个响应中合并响应数据

运维笔记admin11浏览0评论

在一个响应中合并响应数据

在一个响应中合并响应数据

我有一个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的一个回复中使用eventBoostResdata。所以我该如何实现?

eventReseventBoostRes是查询结果。

提前致谢。

回答如下:

问题不是很清楚。

但是,听起来你得到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个查询同步运行并且不是最佳查询。您可以对此进行优化以使用promises并并行运行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 )
  });
});

另一方面;这可能应该在查询级别处理。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论