javascript - Wait for loop to finish $.getJSON for each array item before outputting data -


i've got array of names need retrieve data from, , i'm doing $.getjson inside loop. works , can retrieve data, output correct value need use settimeout or similar. i'm wondering if there's more refined way of doing i'm looking achieve.

here's i've got.

var names = ["riotgames", "example"];  var online = [];    (var = 0; < names.length; i++) {    $.getjson('https://api.twitch.tv/kraken/streams/' + names[i], function(data) {      if (data.stream != null) {        online.push(data.stream.channel.display_name);      };    });  }    console.log(online) // outputs []    settimeout(function() {    console.log(online) // outputs correctly  }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

when doing $.getjson, triggering asynchronous requests. means run in background. not wait them finish, callbacks trigger (like event) once request done.

this means cannot access online outside callback(s).

if want "wait" all requests finish, suggest using promises. can use $.when combine requests 1 promise run callback once done.

var names = ["riotgames", "example"]; var promises = [];  (var = 0; < names.length; i++) {     // $.getjson returns promise     promises.push($.getjson('https://api.twitch.tv/kraken/streams/' + names[i])); }  // combine promises // , run callback $.when.apply($, promises).then(function(){     var online = [];      // callback passed result of each ajax call parameter     for(var = 0; < arguments.length; i++){         // arguments[i][0] needed because each argument         // array of 3 elements.         // data, status, , jqxhr object         online.push(arguments[i][0].stream.channel.display_name);     }      console.log(online); }); 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -