Twitch project - is the problem with my when/then?

Hello. My approach here is to do the getJSON calls and put the relevant info into an array of objects, usersInfo, one for each username. I’ll then build up the HTML stuff using this array.

Anyway, my problem is the usual one - the getJSON (just doing one of them for now) isn’t sending the data back in time. I’ve read about when/then on the forum and tried it. No luck. Can you help please?

This is the pen: http://codepen.io/lpgm/pen/evOBxW

$(document).ready(function() {

	var users = ["esl_sc2", "lpgm", "ogamingsc2", "cretetion", "freecodecamp", "storbeck", "habathcx", "robotcaleb", "noobs2ninjas", "brunofin", "comster404", "medrybw"];
	var usersInfo = [];

	function request(url) {
		return $.getJSON(url);
	}

	function lookUpUsers() {
		for (var i = 0; i < 2; i++) { // Just doing two for now... 
			var urlUsers = "https://wind-bow.gomix.me/twitch-api/users/" + users[i] + "?callback=?";
			var urlStreams = "https://wind-bow.gomix.me/twitch-api/streams/" + users[i] + "?callback=?";
			var userObj = {};
			$.when(request(urlUsers)).then(function(jsonUsers) {
				userObj.username = jsonUsers[name];
				console.log(userObj.username);
				if (jsonUsers.hasOwnProperty("error")) {
					userObj.exists = "no";
				} else {
					userObj.exists = "yes";
					userObj.link = "https://www.twitch.tv/" + jsonUsers[name];
					// Eventually set the other stuff... 
				}
			});
			usersInfo.push(userObj);
			console.log(userObj);
		}
	}

	lookUpUsers();

});

One thing is It looks like you’re pushing into usersInfo outside of then() so this will happen before the API calls are finished.

Good point! Thanks. That’s helped a bit…

This might get you rolling a bit. I took some liberties with your code to make it easier (for me) to read. I also took out the second user in your list because it throws a bad response for some reason.

So urlUsers and urlStreams now act as promises and you can pass both into when at the same time. When both are resolved the then() block will execute.

Then we set the username and push the object into a userObjs array.

but NOTE:

each time you iterate one more object is added to your userObj array. You probably ONLY want to proceed with your next function when ALL of the objects are in your array. So you will have to thikn about how to implement this. Hope this helps

	function lookUpUsers() {
		for (var i = 0; i < 2; i++) {
			var urlUsers = $.ajax("https://wind-bow.gomix.me/twitch-api/users/" + users[i]);
			var urlStreams = $.ajax("https://wind-bow.gomix.me/twitch-api/streams/" + users[i]);
			var userObjs = [];
			$.when(urlUsers, urlStreams).then(function(jsonUsers, jsonStreams) {
                //im only doing stuff with jsonUsers but you can do what you wish with jsonStreams
				let username = jsonUsers[0].name;
				userObjs.push({name: username})
				console.log(userObjs);
			});
		}
	}

Thanks for looking at this.

I haven’t completed all the functionality yet, but I’m well on the way. A couple of things solved the API problems.

  1. I hadn’t come across ‘let’ before. I understand it limits scope, and this helped a lot.

  2. I actually abandoned the when/then thing. I was too caught up with getting all the user info into my array of objects. Instead, I now just grab the static info first from the first API. And then get the status info from the second API when I build up the HTML and output the results. This seems to ‘put distance’ between the API calls and I manage to get all the info correctly.

Here’s the new code:

$(document).ready(function() {

	var users = ["esl_sc2", "lpgm", "ogamingsc2", "cretetion", "freecodecamp", "storbeck", "habathcx", "robotcaleb", "noobs2ninjas", "brunofin", "comster404", "medrybw"];
	var userObjects = [];

	function lookUpUsers() {
		for (var i = 0; i < users.length; i++) {
			let userURL = "https://wind-bow.gomix.me/twitch-api/users/" + users[i];
			let userObj = {};
			userObj.username = users[i];
			$.getJSON(userURL, function(json1) {
				if (json1.hasOwnProperty("error")) {
					userObj.exists = "no";
				} else {
					userObj.exists = "yes";
					userObj.logo = json1["logo"];
					userObj.display = json1["display_name"];
					userObj.link = "https://www.twitch.tv/" + json1["name"];
				}
				userObjects.push(userObj);
			});
		}
	}

	$("#allButton").on("click", function() {
		$("#userList").html('');
		userObjects.forEach(function(user) {
			if (user.exists == 'yes') {
				let streamURL = "https://wind-bow.gomix.me/twitch-api/streams/" + user.username;
				let status = "They're offline at the moment";
				$.getJSON(streamURL, function(json2) {
					if (json2["stream"]) {
						status = json2["stream"]["channel"]["status"];
					}
					$("#userList").append('<div class="box4 row"><div class="col-md-1"><img src="' + user.logo + '" alt="BLANK" height="50" width="50"></div><div class="col-md-2"><a href="' + user.link + '" target="_blank"><p><em>' + user.display + '</em></p></a></div><div class="col-md-7"><strong>' + status + '</strong></div></div>');
				});
			} else {
				$("#userList").append('<div class="box4"><p><em>' + user.username + '</em> doesn\'t exist (any more)</p></div>');
			}
		});
	});

	$("#onlineButton").on("click", function() {
		$("#userList").html('');
	});

	$("#offlineButton").on("click", function() {
		$("#userList").html('');
	});

	lookUpUsers();

});