简体   繁体   English

如何并行运行API调用(Node.js)

[英]How to Run an API Calls in Parallel (Node.js)

I am trying to run some API calls in parallel, but am having problems since I am trying to call a function again before the API data has been returned. 我试图并行运行一些API调用,但是遇到了问题,因为我试图在返回API数据之前再次调用函数。

I am thinking that I could possibly use the new command in Node, but am not sure how to structure it into this scheme. 我以为我可以在Node中使用new命令,但是不确定如何将其构造到该方案中。 I am trying to avoid recursion, as I already have a recursive version working and it is slow. 我正在尝试避免递归,因为我已经有一个递归版本,并且运行缓慢。

Currently I am trying to this code on the server. 目前,我正在尝试在服务器上使用此代码。

loopThroughArray(req, res) { 
  for(let i=0; i<req.map.length; i++) {
    stack[i] = (callback) => {
      let data = getApi(req, res, req.map[i], callback)
    }
  }

  async.parallel(stack, (result) => {
      res.json(result)
  })
}

.... ....

function getApi(req, res, num, cb) {
  request({
    url: 'https://example.com/api/' + num
  },
  (error, response, body) => {
    if(error) {
      // Log error
    } else {
      let i = {
        name: JSON.parse(body)['name'],
        age: '100'
      }
      console.log(body) // Returns empty value array.length > 1 (req.map[i])
      cb(i)
    }
  })

Is there a way to spawn new instances of the function each time it's called and accumulate the results to send back as one result to the client? 有没有一种方法可以在每次调用时生成该函数的新实例,并累积结果以将其作为一个结果发送回客户端?

Here's an example of calling Web APIs (each with different parameters), using the Async library, we start by creating an array of N function variables. 这是一个使用Async库调用Web API(每个都有不同参数)的示例,我们首先创建N个函数变量的数组。

const async = require('async');
const request = require('request');

//Set whatever request options you like, see: https://github.com/request/request#requestoptions-callback
var requestArray = [
    {url: 'https://httpbin.org/get'},
    {url: 'https://httpbin.org/ip'}
];

let getApi = function (opt, callback) {
    request(opt, (err, response, body) => {
        callback(err, JSON.parse(body));
    });
};

const functionArray = requestArray.map((opt) => { 
    return (callback) => getApi(opt, callback); 
});

async.parallel(
    functionArray, (err, results) => {
        if (err) {
            console.error('Error: ', err);
        } else {
            console.log('Results: ', results.length, results);
        }
});

You can easily switch the Url and Query values to match whatever you need. 您可以轻松切换Url和Query值以匹配所需的内容。 I'm using HttpBin here, since it's good for illustrative purposes. 我在这里使用HttpBin,因为它很好地用于说明目的。

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

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