使用Node.js的多个API请求

时间:2018-09-26 07:22:58

标签: javascript node.js express

我试图在for循环中调用多个外部api,但是根据结果,我只从for循环中获得了一次迭代,将响应发送回去。

是的,它不是处理多API请求的正确方法,请提出最佳方法,因为它必须是顺序要求/要求

第一个请求-调用以查找相应的api。响应保存数据以将其馈送到两个for循环内的api中。

For-loop第二API请求-向第三API请求提供数据。

class ItemVariationSerializer(serializers.ModelSerializer):
    item = ItemsSerializer(read_only=True)
    class Meta:
        model = ItemVariation
        fields ='__all__'

1 个答案:

答案 0 :(得分:2)

如果只需要从用户的请求中获取一个号码,然后以相同的次数发出相同的http请求,则应该这样做。我从crocks那里引入了一个没有意义的map助手,使事情变得容易一些。

您可能需要在各处进行一些调整,尤其是在最后的then子句中

const map = require('crocks/pointfree/map');

const app = express();

app.use(bodyParser.json());

const range = integer => [...new Array(integer).keys()]
const replicate = (i, x) => range(i).fill(x)

const handleError = error => {
  logger.debug(`['${pid}'] ${error.reponse.error}`)
  return error;
}

const getMaterialURIs = response =>
  replicate(response.body.floor.length, `http://localhost:8080/material/q=${response.body.material}`)

const processMaterialResponse = response => {
  doSomethingWithMaterial(response.body)
  return response;
}

const getSiteValueURI = response =>
  `http://localhost:8080/value/q=${response.body.value}`;

const processSiteValueResponse = response => {
  doSomethingWithSiteValue(response.body)
  return response;
}

app.post('/building/', function (req, res) {
  const uri = 'http://localhost:8080/site/';
  const body = JSON.stringify(req.body);
  const method = 'POST';
  const headers = { 'Content-Type': 'application/json' };

  // First External API Call
  Request({uri, body, method, headers})
    // 1: fetch to derive the material URI
    .then(getMaterialURIs)
    // 2: fetch from that material URI
    .then(map(Request.get))
    .then(Promise.all)
    // 3: process the material response
    .then(map(processMaterialResponse))
    // 4: derive the siteValueURI 
    .then(map(getSiteValueURI))
    // 5: fetch the siteValueURI
    .then(map(Request.get))
    .then(Promise.all)
    // 6: process the site value response
    .then(map(processSiteValueResponse))
    .catch(handleError)
    .then(response => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end('{"material":"materialquerystring","value":"valuequerystring"}');
    });
});