Reputation: 816
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();
Upvotes: 0
Views: 734
Reputation: 2385
setTimeout
is not the same as sleep
. It's a way to set a callback to happen in x milliseconds. You're passing null as the callback, and infinitely looping in the while
loop, never relinquishing the thread to the http calls.
Edit: I would recommend looking into the async library for doing things like "wait for these three callbacks to finish".
Upvotes: 2
Reputation: 66560
You can fix this by using recursive function that call itself using setTimeout:
(function loop() {
if (count < 3) {
setTimeout(loop, 1000);
console.log('waiting..');
} else {
printAll();
}
})();
Upvotes: 0