workshopper/learnyounode

Exercise 9 - Juggling Async (Alternate Solution)

SidShenoy opened this issue · 3 comments

I thought that the exercise involved using 'callbacks' as you guys had stressed on the fact that callbacks lie at the core of nodeJS. Here is my alternate solution:

var http = require("http");
var bl = require('bl');
var arg_index = 2;
var count = 3;
function http_get(callback)
{
	http.get(process.argv[arg_index++], function(resp){
				resp.setEncoding("utf8");
				resp.pipe(bl(function(err, data){
						if(err) console.error(err);
						var str = data.toString();
						console.log(str);				
				}));
											
				if(arg_index!=2+count)			
				callback(callback);
	}).on('error',console.error);
}
						
http_get(http_get);

I have done something similar. But after seeing the "official solution", I realized my approach was not taking advantage of the asynchronous operation.

I mean, the "2nd get" has to wait for a response from "1st get", and the "3rd get" has to wait for a response from the "2nd get".

can anyone tell why my solution doesn't work? while its some what similar to official solution ..
var http = require('http');
var bl = require('bl');
let count = 0;
const results = [];

for (let i = 0; i < 3; i++) { // what makes the difference by adding a function here, instead of for loop?
http.get(process.argv[i + 2], function (res) {
res.setEncoding('utf8');
res.pipe(bl(function (err, data) {
if (err){
return console.error(err);
}
results[i] = data.toString();
count ++;
if (count == 3) {
printResults()
}
}));
});

}

function printResults() {
for (let i = 0; i < 3; i++) {
console.log(results[i]);
}
}

@sidorares You are logging as soon as the network request is complete console.log(str); which might not always be in order.