-1

What I want to do is, after the document had been loaded I want to call function that get data from API and then call another function that Display this data in html document, I tried to call the function inside the document ready block but nothing work I don't know what to do any help I will be appreciated. her's my code:

var _userList = [];
$(document).ready(function() {
    getData();
    toHtml();
});
function getData() {
var userName = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
userName.forEach(function(user) {
    $.ajax({
        type: "GET",
        url: " https://wind-bow.glitch.me/twitch-api/users/" + user,
        success: function(data) {
            $.ajax({
                type: "GET",
                url: " https://wind-bow.glitch.me/twitch-api/streams/" + user,
                success: function(data1) {
                    data.st = data1;
                }
            });
            _userList.push(data);
            // console.log(data);
        }
    });
});
function toHtml() {
_userList.forEach(function(item) {
    var html = '<div class="user" id="' + item.display_name + '">' +
        '<div class="user-name-img">' +
        '<div class="user-img">' +
        '<img src="' + item.logo + '" alt="" srcset="">' +
        '</div>' +
        '<div class="user-name">' +
        '<h4>' + item.display_name + '</h4>' +
        '</div>' +
        '</div>';
    $(".content-body").append(html);
    if (item.st.stream != null) {
        var str1 = '#' + item.st.display_name + ' .user-img img';
        $(str1).addClass('active');
        var str2 = '#' + item.st.display_name + ' .user-name';
        $(str2).append('<h5><i class="fa fa-video-camera" aria-hidden="true"></i></h5>');
        $(str1.slice(0, str1.indexOf(' '))).addClass('act');
    }
});
}

1 Answers1

0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

You should nest your toHTML function in $.ajax({ success:

However since you are sending mulitiple get requests to twitch, you should consider the following:

  1. Minmize the number of requests so that twitch will not flag you as brute force attacker. put ajax in a loop is generally not a good idea
  2. Since you are creating async functions, you may want to consider using await/promise to control overall workflow
Chris Chen
  • 1,228
  • 9
  • 14