简体   繁体   中英

Adding array out of GET request to existing object returns empty array but getting response

I'm trying to add an array out of a json file i'm getting as a response request to an existing object player (which represents every object in an array called players). This returns an empty array. I have no idea what I'm doing wrong. I'm getting the response but when I want to add it to the player object it goes wrong.

For the full code check https://ide.c9.io/kyriediculous/learnyounode

File : playergamelogs.js

PS.: My code is probably dreadful, any tips are welcome.

Thank you all

players.forEach(function(player) {
    var log = [];
    var id = parseInt(player.playerId,10);
    var url = "http://m.mlb.com/lookup/json/named.sport_hitting_game_log_composed.bam?game_type=%27R%27&league_list_id=%27mlb%27&player_id="+id+"&season=2016&sit_code=%271%27&sit_code=%272%27&sit_code=%273%27&sit_code=%274%27&sit_code=%275%27&sit_code=%276%27&sit_code=%277%27&sit_code=%278%27&sit_code=%279%27&sit_code=%2710%27&sit_code=%2711%27&sit_code=%2712%27";
    player["gameLogs"] = log; 
    // console.log(id);  
    request.get({
        url: url,
        json: true,
        headers: {'User-Agent': 'request'}
    }, function (err, res, data) {
        if (err) {
            console.log('Error:', err);
        } else if (res.statusCode !== 200) {
            console.log('Status:', res.statusCode);
        } else {
            data
           .sport_hitting_game_log_composed
           .sport_hitting_game_log
           .queryResults
           .row
           .forEach(function(game) {
               log.push(game);
           });
        }
    });
});

Returns

kyriediculous:~/workspace $ node playergamelogs
{ firstName: 'DJ',
  lastName: 'LeMahieu',
 playerId: '518934',
 team: 'Colorado Rockies',
  gameLogs: [] }

moved player["gameLogs"] = log; inside of the get callback like in my original version.

It appears there never was a problem, I was console logging before the callback finished retrieving the data so it was never added to the object at the time I called console.log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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