For-loop with API query

For-loop with API query
0

#1

Hi! Could someone help me understand why images come out empty after all the looping is done? It has all the data at the end of the last loop, but comes out empty after the looping is over.

$( document ).ready(function() {
var names = ["ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var status =[];
var images = [];

// list of images
for (var i=0; i<names.length;i++){
       $.ajax({url: "https://wind-bow.glitch.me/twitch-api/users/" + names[i], success: function(result){
        status.push(result.logo);

 }}
);

} 
});

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Also, I have questions like this all the time, if anyone is same lost as me, let’s stay in touch!


#4

Where exactly are you putting data into the images array?


#5

They’re not, but I think I understand what’s happening. Are you checking the status array in the console? That would not show you the contents as you expect.


#6

Nowhere at the moment, this was supposed to go to images, but I thought maybe it does not work, because images is a sort of keyword, so it goes to status now.


#7

Thanks! So I cannot actually push anythign to array with my code?


#8

You can, but the issue is viewing the array in the console. Chances are your browser is running console.log(status) before the HTTP calls have finished, so it’s still empty at that point. The larger issue here is that you don’t want to push to an array. Handle everything in your callback function. Check my Codepen above for an example.


#9

I did, it helps a lot! I just wanted to make sure I understand where I have the problem.


#10

Can I ask something else also? The loop generates several separate divs, but why does the ajax function push everything into the last div?

$( document ).ready(function() {
 
var nicks = ["com2ususa","ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
 
 for (var i=0; i<nicks.length;i++){
   var ni = nicks[i];
       $("body").append("<div id=" + ni + "></div>");
 $.ajax({url: "https://wind-bow.glitch.me/twitch-api/users/"+ni, success: function(result){
       $("#"+ ni).append("<img width='50px' src='" + result.logo+ "'' />");
          $("#"+ ni).append(result.display_name);
          }});  };
 
 });
 

The codepen where you can see the result is here: https://codepen.io/Leighenne/pen/NayXQb


#11

Because you for loop finishes before the data comes back from the API call. Even though you create a div for each user, on the last iteration of the for loop, ni = “noobs2ninjas”. So when the API finally gets called (after the for loop has incremented i , it appends everything to the same div (where id=“noobs2ninjas”).

The $.ajax function is asynchronous, so other code can keep processing and then when the data successfully comes back, the callback function (defined by the success property) will run.

Since the username is in result.display_name, you could do something like:

      success: function(result) {
        var name = result.display_name;
        $("#" + name).append("<img width='50px' src='" + result.logo + "'' />");
        $("#" + name).append(result.display_name);
      }

#12

Ok, I am a bit of a noob, so I thought a loop will only go onto new step and increment after the previous one is done. Anyway to control for that?


#13

The for loop does exactly that, but since the $.ajax function is asynchronous, it does not prohibit the for loop from continuing to iterate through the array.


#14

Thanks! I have solved it with jQuery.each in the end.