Twitch JSON API - Problem with holding data

Hi there,

I’m having problems with my Twitch app. I can do the ajax requests and receive data which I store in an array. But somehow I lose all that data in my array by the end of the program. I don’t know why that is happening.

Can anyone have a look at my code and see what I’m doing wrong?

https://codepen.io/johancleve/pen/QMZaBE

AJAX requests are asynchronous. This means that they start when you expect them to start but the script doesn’t wait for them to finish (because you don’t know how it long it’ll take to get data back from the server). The script continues and when the requests are done, their callbacks are called. So what’s happening in your case is that your final console.log(users) runs before the requests are finished and your users array is empty.

There are two ways to work with this. You either make your UI changes inside the successHandler or your put $.ajaxSetup({async: false}) before your first request to make the requests synchronous (to run in the order you expect it to run). I do not recommend the second approach, it’s generally avoided unless there is a good reason to use it because the longer your request takes to complete the longer it holds your script from running.