0

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

Eddie
  • 26,593
  • 6
  • 36
  • 58
whatscool
  • 317
  • 2
  • 18
  • 2
    Possible duplicate of [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) – Jared Smith Apr 18 '19 at 15:17
  • 2
    Sounds like you're mixing up `success` and `then`. Don't use both, use either of these, but not both together. `.then`, in fact, will be called upon a success call. – briosheje Apr 18 '19 at 15:19
  • 1
    What does your output for myOpponents look like. – GifCo Apr 18 '19 at 15:20
  • 1
    Please try with this code: https://pastebin.com/qHWAByeQ I've cleaned it up a bit, it should work as intended. – briosheje Apr 18 '19 at 15:24
  • @briosheje Thank you very much. I really appreciate that – whatscool Apr 18 '19 at 18:02
  • @briosheje I get an error on results.forEach:not an array. If I console.log it, it's a promise object instead. how am I supposed to access the value of the promise? – whatscool Apr 18 '19 at 18:08
  • That's weird, it should work since the $.ajax call is returning a promise array. Perhaps jQuery acts differently, so you may try to replace `Promise.all` with `$.when`: https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – briosheje Apr 19 '19 at 06:35

1 Answers1

1

Try this:

async function someFunc(userID) {
  let myLeagues = [];
  let myOpponents = [];

  try {
    const results = await $.ajax({
      type: "get",
      url: "/api/user/" + userID,
      dataType: "json"
    });

    results.forEach(element => {
      if (element.short_name == null) {
        myLeagues.push(element.id);
      }
    });

    let leagues = myLeagues.map(leagueid => {
      return $.ajax({
        type: "get",
        url: "/api/league/" + leagueid,
        dataType: "json"
      })
    })

    let leagueDatas = await Promise.all(leagues);

    leagueDatas.forEach(val => {
      if (val.standings.results.length < 30) {
        val.standings.results.forEach(element => {
          myOpponents.push(element.player_name)
        });
      }
    })

    myOpponents.forEach(opponent => {
      console.log(opponent)
    });
  } catch (e) {
    // handle error
  }
}
someFunc(1)
1565986223
  • 6,420
  • 2
  • 20
  • 33
  • Hi. Thanks for writing this. I get val is undefined in the leagueDatas.map. The ajax call in leagues works because I can give it a success function and see the data, but it seems like the promise never works – whatscool Apr 19 '19 at 22:26
  • 1
    What is the result of console.log(leagues) and leagueDatas, it's hard to guess the structure – 1565986223 Apr 20 '19 at 00:15
  • If I console.loge(leagues) or leagueDatas it's an array of four undefined objects. If I put a success function in the AJAX call and console.log that, it evaluates to the object. It seems to be failing on the promise – whatscool Apr 20 '19 at 11:35
  • 1
    could you link to some fiddle, the output of `results` (first await) – 1565986223 Apr 21 '19 at 07:44
  • 1
    sorry my bad, `return` was missing in `myLeagues.map` updated answer check now. – 1565986223 Apr 21 '19 at 18:57
  • Thank you so much man, I really appreciate it. The return makes sense to me, also – whatscool Apr 21 '19 at 19:01