简体   繁体   English

在多次API调用之后,Node Express 4发送响应

[英]Node Express 4 send a response after multiple API calls

I am building a NodeJS server using Express4. 我正在使用Express4构建NodeJS服务器。 I use this server as a middleman between frontend angular app and 3rd party API. 我将此服务器用作前端角度应用程序和第三方API之间的中间人。 I created a certain path that my frontend app requests and I wish on that path to call the API multiple times and merge all of the responses and then send the resulting response. 我创建了前端应用程序请求的特定路径,并希望在该路径上多次调用API并合并所有响应,然后发送结果响应。 I am not sure how to do this as I need to wait until each API call is finished. 我不确定如何执行此操作,因为我需要等待每个API调用完成。 Example code: 示例代码:

app.post('/SomePath', function(req, res) {
  var merged = [];
  for (var i in req.body.object) {
    // APIObject.sendRequest uses superagent module to handle requests and responses
    APIObject.sendRequest(req.body.object[i], function(err, result) {
      merged.push(result);
    });
  }
  // After all is done send result
  res.send(merged);
});

As you can see Im calling the API within a loop depending on how many APIObject.sendRequest I received within request. 如您所见,我根据一个请求中收到了多少APIObject.sendRequest在一个循环中调用API。

How can I send a response after all is done and the API responses are merged? 完成所有操作并合并API响应后,如何发送响应?

Thank you. 谢谢。

Check out this answer , it uses the Async module to make a few requests at the same time and then invokes a callback when they are all finished. 看看这个答案 ,它使用Async模块同时发出一些请求,然后在所有请求完成时调用回调。

As per @sean's answer, I believe each would fit better than map . 按照@sean的回答,我相信each人都比map更合适。

It would then look something like this: 然后看起来像这样:

var async = require('async');
async.each(req.body.object, function(item, callback) {
  APIObject.sendRequest(item, function(err, result)) {
    if (err)
      callback(err);
    else
    {
      merged.push(result);
      callback();
    }
  }
}, function(err) {
     if (err)
       res.sendStatus(500); //Example
     else
       res.send(merged);
});

First of all, you can't do an async method in a loop, that's not correct. 首先,您不能在循环中执行异步方法,这是不正确的。

You can use the async module's map function . 您可以使用async模块的map函数

app.post('/SomePath', function(req, res) {
  async.map(req.body.object, APIObject.sendRequest, function(err, result) {
    if(err) {
      res.status(500).send('Something broke!');
      return;
    }
    res.send(result);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM