简体   繁体   English

node.js js中的学习题,不是异步的吗?

[英]Learning question in js at node.js , isn't it asynchronous?

I just started to learn Node.js and I need help: At the following code that runs on Node why it is stuck in a loop while it supposedly an asynchronous method?我刚开始学习 Node.js 并且我需要帮助: 在 Node 上运行的以下代码中,为什么它卡在一个循环中,而它应该是一个异步方法? and also not waiting the interval.也没有等待间隔。

class FuelBurner{
constructor(){
    console.log("construction set");
    this.fuel=0;
    this.rate=2.0;
    this.polluted=0.0;
}

run(){
    
    while (true){
        console.log("i run");
        setTimeout( function (){this.polluted+=this.rate},1000);
        this.fuel--;
        
    }
}

get_pollution(){
    return this.polluted;
}
}
console.log("Hello");
machine = new FuelBurner();
machine.run();
console.log("Why it never gets here?");

Asynchronous operations in JavaScript are put in a queue and only addressed by your code again when the main event loop isn't busy with something else. JavaScript 中的异步操作被放入队列中,并且仅当主事件循环不忙于其他事情时,才由您的代码再次处理。

You enter the while loop and pass a function to setTimeout .您进入 while 循环并将 function 传递给setTimeout

Then the rest of the loop runs, and the loop starts again.然后循环的rest运行,循环又开始。

About a second later, the first timeout finishes and the function is put on the queue to run when the main event loop is free.大约一秒钟后,第一次超时结束,当主事件循环空闲时,function 被放入队列以运行。

The main event loop is still running the while loop, and will do forever since the condition is always met.主事件循环仍在运行while循环,并且将永远运行,因为条件总是满足。 It never becomes free.它永远不会免费。 It never pulls the function off the queue to run it.它永远不会将 function 拉出队列来运行它。

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

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