简体   繁体   English

将多个 http.requests 中的 arrays 组合成一个数组

[英]Combining arrays from multiple http.requests into one array

I'm trying to wrap my head around why this loop of https.requests isn't working.我试图弄清楚为什么 https.requests 的这个循环不起作用。

I'm trying to make 5 http requests every minute.我试图每分钟发出 5 个 http 请求。 Every http GET request calls the function processRequest() as a callback, and every processRequest() returns an array from the request, let's call it resultsArray.每个 http GET 请求都会调用 function processRequest() 作为回调,并且每个 processRequest() 从请求中返回一个数组,我们称之为 resultsArray。 I'd like to be able to produce one array or object every minute that is the concatenation of all 5 "resultsArray"s from the 5 http requests, but I'm having trouble figuring out how to declare what variables where.我希望能够每分钟生成一个数组或 object,这是来自 5 个 http 请求的所有 5 个“resultsArray”的串联,但我无法弄清楚如何在哪里声明哪些变量。 Here is what I have tried:这是我尝试过的:

The CronJob: CronJob:

var CronJob = require('cron').CronJob;
var tripDataFinal= new Object();

function makeRequest (){
    var urlCounter = 0 ; 
    var feedsList = ["urlA", "urlB", "urlC", "urlD", "urlE"];
    feedsList.forEach((feedToCheck,i)=>{
        options = {
            host: 'host',
            path: feedToCheck 
        }   
        https.request(options, function(response){
            processRequest(response, i, urlCounter, resultsArrayAll);}).on('error', (e) => {
        console.log("Error!"); console.error(e);}).end();   
    })

}
new CronJob('* * * * * *', makeRequest
, null, true, 'America/New_York'); 

The function processRequest() defined in a separated require() file: function processRequest() 定义在单独的 require() 文件中:

module.exports = {


processRequest : function(response, feedNumber, urlCounter, tripDataFinal) {
        urlCounter++;
        //do stuff to 'response' to produce a result called resultsArray
        resultsArrayAll["array"+urlCounter] = resultsArray;
        console.log(urlCounter);
        if (urlCounter == 5){
            urlCounter = 0 ; 
            return concat(resultsArrayAll.array0
                        , resultsArrayAll.array1
                        , resultsArrayAll.array2
                        , resultsArrayAll.array3
                        , resultsArrayAll.array4);
        }
        else return resultsArrayAll;

    }}

The problem is that 'urlCounter' (which is how I count which request of the 5 I'm on) doesn't seem to be advancing past 1. What (maybe multiple things) am I doing wrong?问题是'urlCounter'(这是我如何计算我在5个请求中的哪个请求)似乎没有超过1。我做错了什么(可能是多件事)?

Thanks谢谢

You can wrap your http.request in a Promise and then do Promise.all() , like this:您可以将http.request包装在Promise中,然后执行Promise.all() ,如下所示:

function makeRequest (){
    var urlCounter = 0 ; 
    var feedsList = ["urlA", "urlB", "urlC", "urlD", "urlE"];
    var requestPromises = feedsList.map(function(url){
        return new Promise(function (resolve, reject){
            options = {
                host: 'host',
                path: feedToCheck 
            }   
            https.request(options, function(response){
                resolve(response);
            }).on('error', (e) => {
                reject(e);
            }).end();   
        });
    });

    Promise.all(requestPromises)
        .then(function(resultsArray){
            console.log('Results:', resultsArray);
        })
        .catch(function(e) { console.error(e); });
}

So here, in resultsArray you will have 5 responses from 5 requests (in the order they were made), and you can do whatever you want with them here, ex passing the array to the processRequest() function or something.因此,在这里,在resultsArray中,您将收到来自 5 个请求的 5 个响应(按发出的顺序),您可以在这里对它们做任何您想做的事情,例如将数组传递给processRequest() function 或其他东西。

You can write your logic here no need to rest the urlCounter inside processRequest你可以在这里写你的逻辑不需要rest urlCounter里面processRequest

var CronJob = require('cron').CronJob

function makeRequest () {
  var urlCounter = 0
  var feedsList = ['urlA', 'urlB', 'urlC', 'urlD', 'urlE']
  var resultArray = []
  feedsList.forEach((feedToCheck, i) => {
    options = {
      host: 'host',
      path: feedToCheck
    }
    https.request(options, function (response) {
      const result = processRequest(response) // do processing of response and returns a array
      resultArray.concat(result) // concat all results here
    })
  })
}
new CronJob('* * * * * *', makeRequest, null, true, 'America/New_York')

If you want to use concated resultArray you need to use promises here once you done with the all the request you can resolve that promise with resultArray and can use it after it.如果您想使用连接的resultArray ,您需要在完成所有请求后在此处使用 Promise,您可以使用resultArray解决 promise 并可以在它之后使用它。

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

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