Need help with my 'Twitchtv' - Project

Need help with my 'Twitchtv' - Project
0.0 0

#1

Hello! :grinning:
I am having trouble with my code…
I am collecting data through my ‘getInfo()’-function and returning it as an array.
I then try to access this data in my ‘createHTML()’-function. But I can’t access it…
My for-loop should console.log ‘Hi’, but nothing happens and if I try to access the array like ‘test[0]’ it says ‘undefined’.
I really don’t know why… :confused:

Here is the link to my pen: https://codepen.io/butterfliege/pen/MVVqZZ

Can someone please help me?


#2

I don’t understand your code. Why do you need a Promise?


#3

I thought it would be helpful to call ‘createHTML()’ only when the ‘getInfo()’ function was successful…
That’s why I used the promise.

Do you think it would make more sense to delete the promise?


#4

My version was a lot simpler. I’m just not sure what the Promise code does. Can you explain?


#5

The code in getInfo is still async even using the getJSON promise style. so the value returned info will still be an empty array. Now because of closure that returned array may get filled in which will lead to some really confusing behavior.


#6

@JohnnyBizzel
I realize I am not completely sure myself what my code does… :zipper_mouth_face:

@silgarth
Could you help me fix the problem with the empty array? Is the promise the problem or the code inside of ‘getInfo()’?

).fail(function( jqxhr, textStatus, error ){
console.log(error);
});

#7

The function will call getJSON and then return the empty array. The code inside the .then will run at a later time.
You can change getInfo to return a promise as well.

function getInfo() {
   var info = [];
   return new Promise(function(resolve, reject) {
     $.getJSON(URL).then(function(data) {
       // fill in info
       // if you want to make two $.getJSON - then the second would be here.
       resolve(info);
     })
     .fail(function(){
       reject("error");
     })

#8

This works!
Thank you so much @silgarth!
I guess I need to learn a bit more about promises and closure… :sweat_smile:

@JohnnyBizzel
Thanks to you too! :smiley: