Note: I know I'm probably doing this the wrong way and I'd like any advice about writing it better.
I have a function that, when given a user id, does calls to two APIs to get 1. A list of all the leagues that userid is in. 2. A list of all users in each of those leagues.
$.ajax({
type: "get",
url: "/api/user/" + userID,
dataType: "json",
success: function(response) {
response.leagues.classic.forEach(element => {
if (element.short_name == null) {
myLeagues.push(element.id);
}
});
}
}).then(function() {
myLeagues.forEach(leagueid => {
$.ajax({
type: "get",
url: "/api/league/" + leagueid,
dataType: "json",
success: function(response) {
if (response.standings.results.length < 30) {
response.standings.results.forEach(element => {
myOpponents.push(element.player_name)
});
}
}
});
})
}).then(function() {
console.log(myOpponents);
myOpponents.forEach(opponent => {
console.log(opponent)
});
})
console.log(myOpponents)
outputs an array with all opponents, as expected
console.log(opponent)
two lines later doesn't output anything.
Can you explain why that is, and suggest a better way of writing this whole function? Thanks