javascript - Call function after ajax calls have finished -


this question has answer here:

i'm trying use twitch.tv's api information channels. have different channels im trying information in array iterate through forloop , within loop make $.ajax() each 1 of these channels. after information want these channels store them in object push onto different arrays depending on wether or not channel streaming or offline. issue seems when call display method , change divs html information channels, of requests have not completed yet , reason dont channels added onto page. question should call display function in code , if there better approach im trying achieve. in advance here code. https://jsfiddle.net/bwsvxsdv/4/

<!doctype html> <html>     <head>         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>     </head> <body>     <div class="well">         <h1>twitch.tv api</h1>      </div>      <div class="row">         <div class="col-sm-3 text-center">             name         </div>          <div class="col-sm-9 text-center">             status         </div>     </div>      <div class="channelcontainer">      </div>     <script>         $streamers = ["esl_sc2", "ogamingsc2", "cretetion", "freecodecamp",         "storbeck", "habathcx", "robotcaleb",         "noobs2ninjas", "brunofin", "comster404","zxcxxxxzzxxxxc"];          $onlinechannels = [];         $offlinechannels = [];         $closedchannels = [];         $nonexistantchannels = [];          function getstreaminfo(callback){             for($i=0;$i<$streamers.length;$i++){                 $.ajax({                     name:$streamers[$i],                     length:$streamers.length-1,                     index:$i,                     func: callback,                     url:'https://api.twitch.tv/kraken/streams/'+$streamers[$i],                     datatype:'json',                     success: function(data){                          if(data.stream != null){//if there stream information                             //add online channels                             //console.log("its streaming channel");                             $chaninfo = {"name":this.name,"game":data.stream.game,"status":data.stream.channel.status};                             $onlinechannels.push($chaninfo);                         }else{                             //add offlinechannels                             //console.log("currently not streaming");                             $chaninfo = {"name":this.name,"status":"offline"};                             $offlinechannels.push($chaninfo);                         }                        },                     error: function(data){                         if(data.status === 422){                             //console.log('add closedchannels');                             $chaninfo = {"name":this.name,"status":"account closed"};                             $closedchannels.push($chaninfo);                         }                          if(data.status === 404){                             //console.log('add nonexistantchannels');                             $chaninfo = {"name":this.name,"status":"non existant channel"};                             $nonexistantchannels.push($chaninfo);                         }                     },//end of error                                             complete: function(){                         if(this.index === this.length){                             callback();                         }                     }                 });//end of ajax request              }//end of loop         }//end of function          function displaychannels(){         console.log('doing displaychannels function');         $chans = [$onlinechannels,$offlinechannels,$closedchannels];          $html = "";         for($i =0;$i<$onlinechannels.length;$i++){             console.log("making html");             $html+= '<div class="row"><div class="col-sm-3 text-center">'+$onlinechannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$onlinechannels[$i]["status"]+'</div></div>'          }         for($i =0;$i<$offlinechannels.length;$i++){             console.log("making html");             $html+= '<div class="row"><div class="col-sm-3 text-center">'+$offlinechannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$offlinechannels[$i]["status"]+'</div></div>'          }         for($i =0;$i<$closedchannels.length;$i++){             console.log("making html");             $html+= '<div class="row"><div class="col-sm-3 text-center">'+$closedchannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$closedchannels[$i]["status"]+'</div></div>'          }         console.log($html);         console.log("about add html");         $(".channelcontainer").html($html);         console.log("html added");         }          getstreaminfo(displaychannels);     </script> </body> 

you can use deferred array , call callback when deferred objects have been resolved.

$streamers = ["esl_sc2", "ogamingsc2", "cretetion", "freecodecamp",    "storbeck", "habathcx", "robotcaleb",    "noobs2ninjas", "brunofin", "comster404", "zxcxxxxzzxxxxc"  ];    $onlinechannels = [];  $offlinechannels = [];  $closedchannels = [];  $nonexistantchannels = [];    function getstreaminfo() {      var deferred = [];   // deferred array.      ($i = 0; $i < $streamers.length; $i++) {        deferred.push(          $.ajax({            name: $streamers[$i],            length: $streamers.length - 1,            index: $i,              url: 'https://api.twitch.tv/kraken/streams/' + $streamers[$i],            datatype: 'json',            success: function(data) {                if (data.stream != null) { //if there stream information                //add online channels                //console.log("its streaming channel");                $chaninfo = {                  "name": this.name,                  "game": data.stream.game,                  "status": data.stream.channel.status                };                $onlinechannels.push($chaninfo);              } else {                //add offlinechannels                //console.log("currently not streaming");                $chaninfo = {                  "name": this.name,                  "status": "offline"                };                $offlinechannels.push($chaninfo);              }                  },            error: function(data) {                if (data.status === 422) {                  //console.log('add closedchannels');                  $chaninfo = {                    "name": this.name,                    "status": "account closed"                  };                  $closedchannels.push($chaninfo);                }                  if (data.status === 404) {                  //console.log('add nonexistantchannels');                  $chaninfo = {                    "name": this.name,                    "status": "non existant channel"                  };                  $nonexistantchannels.push($chaninfo);                }              } //end of error						            }) //end of ajax request        );                } //end of loop      return deferred; // return array    } //end of function    function displaychannels() {    console.log('doing displaychannels function');    $chans = [$onlinechannels, $offlinechannels, $closedchannels];      $html = "";    ($i = 0; $i < $onlinechannels.length; $i++) {      console.log("making html");      $html += '<div class="row"><div class="col-sm-3 text-center">' + $onlinechannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $onlinechannels[$i]["status"] + '</div></div>'      }    ($i = 0; $i < $offlinechannels.length; $i++) {      console.log("making html");      $html += '<div class="row"><div class="col-sm-3 text-center">' + $offlinechannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $offlinechannels[$i]["status"] + '</div></div>'      }    ($i = 0; $i < $closedchannels.length; $i++) {      console.log("making html");      $html += '<div class="row"><div class="col-sm-3 text-center">' + $closedchannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $closedchannels[$i]["status"] + '</div></div>'      }    console.log($html);    console.log("about add html");    $(".channelcontainer").html($html);    console.log("html added");  }      var deferredarr = getstreaminfo();  // call callback once ajax calls done  $.when.apply(null, deferredarr).done(function() {    alert("all requests completed!. calling displaychannels");    displaychannels();  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="well">    <h1>twitch.tv api</h1>    </div>    <div class="row">    <div class="col-sm-3 text-center">      name    </div>      <div class="col-sm-9 text-center">      status    </div>  </div>    <div class="channelcontainer">    </div>


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo