0

I would like to know how can I save globally a variable inside the request?

In this case, I am doing multiple requests and I increment every time. I want to use increment variable, outside the request code.

This is my code:

var url ="";

for (i = 0; i <= queries.startDates.length - 2; i++)
{
    var increment;

    //console.log(queries.endDates[i]);
                
    url = `https://api.weatherbit.io/v2.0/history/daily?city=${city}&start_date=${queries.startDates[i]}&end_date=${queries.endDates[i]}&key=${historicalApiKey}`;
    // console.log(url);
    request(url, function(err, response, body) 
                {
                    // On return, check the json data fetched
                    if (err) 
                    {
                        res.render('HistoricalData', { weather: null, error: 'Error, please try again' });
                    } 
                    else 
                    {
                        //console.log(body)
                        let weather = JSON.parse(body);

                        //console.log(weather);
            
                        if (weather == undefined) 
                        {
                            //console.log("ana");
                            res.render('HistoricalData', { weather: null, error: 'Error, please try again' });
                        } 
                        else
                        {
                           var weeklyInfo = structureData(loopThroughDays(weather),organizedTemperaturesMap);
                           //console.log(weeklyInfo.get('Oct'));

                           increment++;
                        }
                    }
                });  

    console.log(increment);
}

In this case, increment will be 0. How can I actually do it? Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tavi
  • 1
  • Sounds like you could use a [session](https://www.npmjs.com/package/express-session) – Phil Oct 26 '21 at 22:32
  • Is this a server? What is the lifetime of this `increment` variable? Does it belong to your whole server? Or does it belong to only one user. Can you show the context that this code is called in and describe how you want to use the `increment` variable later? All of this is important because you are not currently tracking when all the requests in your `for` loop are done so there's no way for any code to reliably use this value. So, we need to know more about what you're trying to do with it and how you're trying to use it. – jfriend00 Oct 26 '21 at 23:34
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Aug 11 '22 at 07:24

0 Answers0