The goal of the following code is to fetch webpages from three sites specified on command line and to display them in the order specified on command line. My first solution (shown below) was to use while loop to wait for three async tasks to finish but the while loop keeps looping forever. I learned that the correct solution was to detect if variable "count" reached 3 inside each async task (also shown below but commented out), not outside async task. But I'm wondering why my initial solution does not work. Can someone point me to the right Javascript specification of something that explains the flaw of my initial solution? Thanks!
var http = require('http');
var bl = require('bl');
var url1 = process.argv[2];
var url2 = process.argv[3];
var url3 = process.argv[4];
var content1;
var content2;
var content3;
var count = 0;
http.get(url1, function (res) {
res.pipe(bl(function (err, data) {
content1 = data.toString();
count++;
// if (count == 3) printAll();
}));
});
http.get(url2, function (res) {
res.pipe(bl(function (err, data) {
content2 = data.toString();
count++;
// if (count == 3) printAll();
}));
});
http.get(url3, function (res) {
res.pipe(bl(function (err, data) {
content3 = data.toString();
count++;
// if (count == 3) printAll();
}));
});
function printAll() {
console.log(content1);
console.log(content2);
console.log(content3);
}
// this while loop loops forever
while (count < 3) {
console.log('waiting..');
};
printAll();
setTimeout()is asynchronous too. It doesn't pause the loop.setTimeoutis async;whileis not. It will cycle a million times through the loop before the firstsetTimeoutconcludes. The correct way to use this is with promises.