workshopper / learnyounode

Learn You The Node.js For Much Win! An intro to Node.js via a set of self-guided workshops.
Other
7.24k stars 1.84k forks source link

Exercise 9 - Juggling Async (Alternate Solution) #625

Closed SidShenoy closed 4 years ago

SidShenoy commented 6 years ago

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);
th-santos commented 5 years ago

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".

PRANAY100 commented 5 years ago

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]); } }

AnshulMalik commented 4 years ago

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