Closed SidShenoy closed 4 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".
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.
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: