Help with Twitch.tv - array of objects with length 0?!

Help with Twitch.tv - array of objects with length 0?!
0

#1

Hi there,

I am working on the Twitch.tv project. I have successfully retrieved data from the api, and can display it as it arrives.

I am also pushing each stream object to myArr as it arrives, so I can sort and otherwise manipulate the data for later presentation. This appears to work. I can log the array to the console and see that it contains 9 stream objects, as expected.

However, when I try later to work on the array, I am getting unexpected results. Further testing reveals that myArr.length = 0. Huh? I don’t understand what is going on here.

Thanks for your help!

My pen is here


#2

That is because you are logging it outside of the callback. This code is run before the http request has finished. So at the point that you are logging it, it is still empty. The “problem” is that your browser updates the logged array, so that it looks like the array is not empty at that point. But it is!

You can check this by quickly clicking the arrow that reveals the content of the array. If you are fast enough you will notice that it is empty at first and after some time the items are added.

EDIT: Behaviour is most likely going to be different in each browser. In firefox beta it seems that the value of the array gets evaluated at the moment you click on it. It won’t change after that. So directly clicking it before it is filled, will result in an empty array. But if you wait a few seconds before clicking (and thus the requests have finished), the console shows the full array.


#3

Thanks, BenGitter. I understand what’s happening now. Is there some good practice to follow, that lets me work with the data in myArr once all the http requests are finished? That is what I am trying to accomplish.


#4

Maybe this helps:


#5

Thank you again - that did help! Onward…