Twitch API - getting around asynchronous calls

Hi,

This project has stumped me for a month now… I finally got it sort of working, but I think due to the asynchronous nature of ajax, each time the page is loaded up, it displays differently. Only on the rare occasion does everything populate correctly.

I’ve been trying to read around this, but I still haven’t figured out how to implement a solution that works for my code. I thought maybe I could do something like this (http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done) but i can’t get it to work.

Here is my pen: https://codepen.io/plasticookies/full/gWOXPw/

Help, please?

Thanks.

You can try nesting the second getJSON call inside the first one.

$.getJSON(url, function(json) {

  // ...

  $.getJSON(url, function(json) {
    // ...
  })

});

but as you can imagine, it can get dirty as you add more getJSON calls.

You can also try using Promises.

1 Like

The nesting won’t guarantee any semblance of order either, at least not when I tried it. I ultimately decided that it wasn’t important enough to me for them to be in order, thus I stopped spending time on that. Hadn’t checked out Promise before tho, thank you for that reference!

I thought what the OP meant by “everything populating correctly” is that, sometimes the images don’t appear. When I nested the second getJSON, it seemed to fix that issue.

Thanks for that! I had briefly thought about nesting because it sounded like it would get dirty, so I’d dismissed the idea. It seems to have done the trick for now though.

I’ll have to figure out how Promises work because I’m still not totally satisfied :stuck_out_tongue: