I am attempting to create a viewer which used the twitch.tv api to check an array of twitch streamers and then post which users are currently online and what they are streaming. I am having some serious trouble figuring out how to work with the asynchronous nature of callbacks.
I want to loop though the api call once for each twitch user in the array. AFTER they have all returned I want to be able to sort through them and list them in order of specific criteria.
After much research I am trying to use promises to do this. However I still cannot manage to figure this out.
I have used this question: How can I wait for set of asynchronous callback functions? and this question: How do I return the response from an asynchronous call? as a guideline but obviously I am still missing something important. I have posted the relevant part of my code. I would appreciate any help/ nudge in the right direction to what I am missing.
$(document).ready(function() {
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff","ESL_SC2", "brunofin"];
var test = [];
function getData(){
var promises = [];
for (var i = 0; i < channels.length; i++) {
promises.push($.getJSON('https://api.twitch.tv/kraken/streams/'+channels[i]+'?callback=?', function(data) {}));
}
$.when.apply($, promises).then(function() {
// returned data is in arguments[0][0], arguments[1][0], ... arguments[9][0]
// you can process it here
for(var j=0; j<promises.length; j++){
//console.log(promises[j].responseJSON);
test.push(promises[j]);
}
}, function() {
// error occurred
conole.log("get data error");
});
}
getData();
console.log("do I have data?: ");
for(var j=0; j<test.length; j++){
console.log(test[j].responseJSON); //This is empty and where I need the data!
}
});