Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDillon Kavanagh
14,296 PointsForeach | For loop Javascript - Treehouse API extension. Issue iterating over the loop for pulling and printing an array
The issue is iterating through the array of users. Appreciate the support.
// Problem: We want to track a users progress each week and display their progress on a chart
// Solution: Use node.js to connect to Treehouse's API and get profile data to print out
var https = require("https");
var usernames = ["dillonkavanagh", "seantrant", "briankershaw", "beatrizbarcelos", "troyou", "dalalalshohaib", "matthewberrill", "stephenhackett", "kathleenkelly"];
// Print out message
function printMessage(username, badgeCount, points){
var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in total.";
console.log(message);
}
function printStats(usernames, points){
var messageLoop = usernames + " has " + points + " points in total!";
console.log(messageLoop);
}
// Print out error messages
function printError(error){
console.error(error.message);
};
// Connect to the API URL's [Handle a database array of usernames] (https://teamtreehouse.com/dillonkavanagh.json
for(var i = 0; i <= usernames.length; i++){
var request = https.get("https://teamtreehouse.com/" + usernames[i] + ".json", function(res){
var body = "";
// console.log(res.statusCode);
// Read the data
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
if(res.statusCode === 200){
try {
var profile = JSON.parse(body);
printStats(usernames[i], profile.points.total)
} catch(error) {
// parse error
printError(error);
}
} else {
// Status Code error
printError({message: "There was an error getting the profile for " + usernames[i] + ". (" + http.STATUS_CODES[res.statusCode] +") "});
}
});
// Connection Error
request.on("error", printError);
// Store / Parse relevant data
// Print data to screen
});
};