I have the following code:
const rp = require('request-promise');
const cheerio = require('cheerio');
const request = require('request')
homeTeam = []; //home team
awayTeam = []; //away team
openOdds = []; //opening odds
currOdds = []; //current odds
awayPerc = []; //away money distribution
homePerc = []; //home money distribution
//sports action API connection
const options = {
url: 'https://api-prod.sprtactn.co/web/v1/scoreboard/mlb?date=20180520',
json: true
}
//sports action money distribution scrape and push to array
request('https://www.actionnetwork.com/mlb/live-odds', function (err, res, html) {
if (!err && res.statusCode == 200) {
var $ = cheerio.load(html);
$('td.text-right.border-left span:first-child').each(function(i, element) {
const awayPercs = $(this).text();
const homePercs = $(this).next().text();
awayPerc.push({awayPercs})
homePerc.push({homePercs})
});
}});
//home team, away team, opening odds, and closing odds API pull
rp(options)
.then((data) => {
const games = data.games
games.forEach((games) => {
games.teams.forEach((teams, i) => {
if (games.home_team_id == games.teams[i].id) {
homeTeam.push({homeTeam: games.teams[i].full_name});
} else if (games.away_team_id == games.teams[i].id) {
awayTeam.push({awayTeam: games.teams[i].full_name});
}
})
games.odds.forEach((odds, i) => {
if (games.odds[i].type == "game" && games.odds[i].book_id == "15") {
currOdds.push({curAway: games.odds[i].ml_away, curHome: games.odds[i].ml_home})
} else if (games.odds[i].type == "game" && games.odds[i].book_id == "30") {
openOdds.push({openAway: games.odds[i].ml_away , openHome: games.odds[i].ml_home})
}
})
})
})
.catch((err) => {
console.log(err);
})
console.log(awayPerc)
Whenever I try to log any of my arrays outside of their respective loops it returns an empty array. If I declare the array outside the function shouldn't I be able to access it's results anywhere? If I log the array within it's respective loop it works fine, but outside it's empty.