Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.