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 trial

JavaScript Node.js Basics (2014) Building a Command Line Application Perfecting: Getting Multiple Profiles

Chad Whitaker
Chad Whitaker
2,677 Points

How would you output each user in the order given inside the user variable?

I'm curious how you would print in the order of input instead of the order of each completed http request.

2 Answers

Shreyash Agarwal
Shreyash Agarwal
9,843 Points

Store each of the variables in an ordered array and then increment a loop to print the array.

How about that?

Juri Hahn
Juri Hahn
3,312 Points

Shreyash Agarwal that won't work most likely. Remember, NodeJS is asynchronous by default for most APIs. So if you do something like

// require all necessary modules...
var users = ['username_1', 'username_2', 'username_x'];
var array = [];

users.forEach(function(username) {
  array.push(profile.get(username));
});

// that will be executed directly without waiting for the previous 
// profile.get(...) function calls inside the loop
array.forEach(function(userData) {
  printMessage(userData);
});

So in that case you won't see anything most likely because when the 2nd array loop is executed the array is still empty. So in order to print them in the original order, one idea would be to wrap each request into a promise and synchronize, that is, make sure that promises are fulfilled (the request has finished and has been processed), the entire array of promises. One JS library to do that would be RSVP.js but there are many others.