Monday, 29 May 2017

Can someone help explain what's happening with Node.js, axios, and callbacks? [duplicate]

This question already has an answer here:

Good day everyone! I'm working on a little project that involves connecting to a weather api and storing the data from a response. I am experience some strange happenings with my code that I do not really understand, so I was hoping maybe someone could explain.

In my script.js, I have a main function which is making serveral calls to an api (specifically in this case lists.locations.lenghth = 2):

var parsedData = {
    wunderData: []
}
function main(){
    for (var i = 0; i < lists.locations.length; i++) {
        requests.getWunderData(locations[i], function(res){
            //console.log(res);
            parsedData.wunderData.push(res);
        });
    }
    console.log(parsedData.wunderData);
}

In my requests.js file, I am handling the get request with axios:

module.exports = {
    getWunderData: function(city, callback){

        var url = "http://api.wunderground.com/api/[key]/hourly10day/q/" + city.state + "/" + city.name + ".json";

        axios.get(url)
            .then(function(res){
                callback(parseWunderData(res, city));
            }).catch(function(err){
                console.log(err);
            })
    },...

Now, what I was attempting to do as you can see in my main() function was to push the data from my get request (after parsing the data).

My parseWunderData function simply returns an array of objects, each containing the values, I want.

function parseWunderData(data, city){
    var parsed = [];
    var forecasts = data.data.hourly_forecast;

    for (var i = 0; i < forecasts.length; i++){
        var loc = city.initals;
        var type = forecasts[i].condition;

        var day = forecasts[i].FCTTIME.mday_padded;
        var month = forecasts[i].FCTTIME.mon_padded;
        var year = forecasts[i].FCTTIME.year;
        var date = month + "/" + day + "/" + year;

        var temp = {
            hour: forecasts[i].FCTTIME.hour,
            temp: forecasts[i].temp.english
        }

        var parsedForecast = new models.GeneralForecast(loc, date, type, temp.temp);
        parsed.push(parsedForecast);
    }

    return parsed;
}

this data is to be turned into a csv/other file later in my script.js file via the main method. So my question is: Why, when I run:

console.log(parsedData.wunderData);

outside of the callback does the wunderData array log as an empty array?

[]

I assume this has something to do with the way get requests work. (synchronous code vs asynchronous code), but I don't really know. I know that I can work with my parsed data within my callback function. (e.g. I know if I log the data from within the callback function, everything works all fine and dandy). I don't have a problem with creating the csv file from within the callback function as that looks the only way my code here will work. But i don't know if this is fine practice or if I'm doing anything poorly here.



via Alexander Werner

No comments:

Post a Comment