简体   繁体   English

Javascript:为什么我不能等待while循环完成异步任务?

[英]Javascript: why can't I wait for async task to finish using while loop?

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. 我的第一个解决方案(如下所示)是使用while循环来等待三个异步任务完成,但是while循环永远保持循环。 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. 我了解到正确的解决方案是检测每个异步任务中的变量“ count”是否达到3(也在下面显示,但已注释掉),而不是异步任务之外。 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? 有人可以指出正确的Javascript规范来解释我最初的解决方案的缺陷吗? 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 not the same as sleep . setTimeoutsleep It's a way to set a callback to happen in x milliseconds. 这是将回调设置为在x毫秒内发生的一种方法。 You're passing null as the callback, and infinitely looping in the while loop, never relinquishing the thread to the http calls. 您将null作为回调传递,并在while循环中无限循环,从不将线程放弃给http调用。

Edit : I would recommend looking into the async library for doing things like "wait for these three callbacks to finish". 编辑 :我建议您查看异步库以执行诸如“等待这三个回调完成”之类的操作。

You can fix this by using recursive function that call itself using setTimeout: 您可以使用使用setTimeout调用自身的递归函数来解决此问题:

(function loop() {
   if (count < 3) {
       setTimeout(loop, 1000);
       console.log('waiting..');
   } else {
       printAll();
   }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM