0

First off, I am new to JS, HTML, and CSS.

When I debug this code, it seems to not run in the order I would expect, top to bottom. What am I doing wrong?

This code is supposed to use the twitch.tv api to find the channels I follow, take their ID, run another ajax call to see if they are live, and if they are live, present them on my html page.

I have tried debugging this and running ajax calls in Postman and the calls do work for the Twitch API and I get the information I want. The problem is, it runs out of order so the code doesnt do what I intend. I tried debugging with Chrome break points and Debugger for Chrome extension in VS Code.

$(document).ready(function() {
    var userID = [];
    var logo = [];
    var status = [];
    var name = [];
    var totalFollowing;

    //Get User IDs for following
    $.ajax({
        type: 'GET',
        url: 'https://api.twitch.tv/kraken/users/Lucidic_/follows/channels?limit=100',
        headers: {
            'Client-ID': 'hidden',
            'Accept': 'application/vnd.twitch.v5+json'
        },
        success: function(followingData) {
            for (var i = 0; i < followingData._total; i++) {
                totalFollowing = followingData._total;
                userID.push(followingData.follows[i].channel._id);
                logo.push(followingData.follows[i].channel.logo);
                status.push(followingData.follows[i].channel.status);
                name.push(followingData.follows[i].channel.display_name);
            }
        }
    });

    var allFollowingURL = "https://api.twitch.tv/helix/streams?";
    for (var i = 0; i < totalFollowing; i++) {
        allFollowingURL.concat("&user_id=" + userID[i])
    }

    $.ajax({
        type: "GET",
        url: allFollowingURL,
        headers: {
            'Client-ID': 'hidden',
            'Accept': 'application/vnd.twitch.v5+json'
        },
        success: function(channelData) {
            if (channelData.data.type = 'live') {
                $("#followerInfo").prepend("<div class = 'row'>" + "<div class = 'col-sm-4'>" + "<img src='" + logo[i] + "'>" + "</div>" + "<div class = 'col-sm-4'>" + name[i] + "</div>" + "<div class = 'col-sm-4'>" + status[i] + "</div></div>");
            }
        }
    });
});

Ashley Grant
  • 10,879
  • 24
  • 36
Lucid
  • 3
  • 1
  • The comments and answer should help you understand promises and async but since you're using jQuery i suggest looking at the documentation for callbacks on the `ajax` function, namely `success`, `error`, and `complete`. – Steven B. Apr 26 '19 at 21:55
  • Practical advice. Call 2nd `$.ajax` form `success` *callback* of the 1st one. – Alex Kudryashev Apr 26 '19 at 22:03

1 Answers1

2

The reason for the code "running out of order" is because the API requests you are making run asynchronously. These requests take time to return with the data, so instead of holding your program hostage while it waits for this request to come back, the program keeps on executing, then goes back to execute the code in the request's call back function once the data has returned.

See more on learning about something called a promise here https://developers.google.com/web/fundamentals/primers/promises. These are very powerful and useful for handling things like http requests.

JamieT
  • 1,177
  • 1
  • 9
  • 19
  • Ok I will look into it. I also just saw I would add "async: false," to stop the asynchronousness – Lucid Apr 26 '19 at 21:48
  • 1
    This is an option, but generally poor practice in most cases as this will indeed hold your execution hostage until the request return. also see about the `await` operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await. – JamieT Apr 26 '19 at 21:49
  • 3
    setting `async` to `false` is a bad practice in 99.9999% of cases – Flash Thunder Apr 26 '19 at 21:53
  • 1
    @JamieTaylorSangerman: upvoted the comment, however *effectively the same* could be seen as an unacceptable simplification. – Wiktor Zychla Apr 26 '19 at 21:53
  • 1
    @WiktorZychla you're right. definitely an over-simplification for most other use cases so I removed that part. – JamieT Apr 26 '19 at 21:55