Skip to content

Instantly share code, notes, and snippets.

@christopherdolan
Forked from Spencer-Allen/09_JugglingAsync.js
Last active August 29, 2015 14:05
Show Gist options
  • Save christopherdolan/3036a5b56be50bf825c3 to your computer and use it in GitHub Desktop.
Save christopherdolan/3036a5b56be50bf825c3 to your computer and use it in GitHub Desktop.
//THE EXERCISE:
//This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get().
//However, this time you will be provided with three URLs as the first three command-line arguments.
//You must collect the complete content provided to you by each of the URLs and print it to the console (stdout).
//You don't need to print out the length, just the data as a String; one line per URL.
//The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.
//MY ISSUE:
//This is problem #9 on LearnYouNode from nodeschool.io
//They've specifically requested I NOT use [async] for this.
//This program runs well, except for *one* issue.
//On line 47, there's a callback in the function aSyncMap
//if I put it inside of the forEach function, it returns data as required, but not in the right order.
//when outside of the forEach, it seems to not get the proper scope of the var "results"
//Any thoughts?
var http = require('http');
var bl = require('bl');
var urls = [];
process.argv.slice(2).forEach(function(item){
urls.push(item)
});
function getter(url, callback){
http.get(url, function(response) {
response.setEncoding('utf8');
response.pipe(bl(function(err, data){
if (err) {
return callback(err);
}
//console.log(data.toString())
callback(data.toString());
}));
});
}
function aSyncMap(array, getter, callback){
var results = {};
var done = false;
array.forEach(function (item, i){
getter(item, function(data){
results[item] = data;
if (done) callback(results);
});
});
done = true;
}
aSyncMap(urls, getter, function(results){
urls.forEach(function(item){
console.log(results[item]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment