简体   繁体   English

nodejs 是如何异步工作的?

[英]How does nodejs works asynchronously?

I get the response from /route1 until /route2 logs "ROUTE2".我从/ route1得到响应,直到/route2记录“ ROUTE2 ”。

But I studied that nodejs puts functions like setTimeout() in external threads and the main thread continues to work.但是我研究了一下nodejs把setTimeout()之类的函数放到了外线程中,主线程继续工作。 Shouldn't the for loop executed in an external thread? for 循环不应该在外部线程中执行吗?

app.get("/route1",(req,res)=>
{
    res.send("Route1");
});

app.get("/route2",(req,res)=>
{
    setTimeout(()=>
    {
        console.log("ROUTE2");
        for(let i=0;i<1000000000000000;i++);
        res.send("Route2");
    },10000);
})

Node.js uses an Event Loop to handle Asynchronous operations . Node.js 使用Event Loop来处理异步操作 And by Asynchronous operations I mean all I/O operations like interaction with the system's disk or network, Callback functions and Timers(setTimeout, setInterval) .我所说的异步操作是指所有I/O 操作,例如与系统磁盘或网络的交互、回调函数和 Timers(setTimeout, setInterval) If you put Synchronous operations like a long running for loop inside a Timer or a Callback, it will block the event loop from executing the next Callback or I/O Operation.如果将同步操作(例如长时间运行的for loop放入 Timer 或回调中,它将阻止事件循环执行下一个回调或 I/O 操作。

In above case both /route1 and /route2 are Callbacks, so when you hit them, each callback is put into the Event Loop.在上述情况下,两个/route1/route2是回调,所以,当你打他们,每个回调放入事件循环。

Below scenarios will give clear understanding on Asynchronous nature of Node.js:以下场景将清楚地了解 Node.js 的异步性质:

  1. Hit /route2 first and within 10 Seconds (Since setTimeout is for 10000 ms) hit /route1首先点击/route2在 10 秒内(因为 setTimeout 为 10000 毫秒)点击/route1

In this case you will see the output Route 1 because setTimeout for 10 secs still isn't complete.在这种情况下,您将看到输出Route 1,因为 10 秒的 setTimeout 仍未完成。 So everything is asynchronous.所以一切都是异步的。

  1. Hit /route2 first and after 10 Seconds (Since setTimeout is for 10000 ms) hit /route1首先点击/route2然后在 10 秒后(因为 setTimeout 是 10000 毫秒)点击/route1

In this case you will have to wait till the for loop execution is complete在这种情况下,您将不得不等到for 循环执行完成

for(let i=0;i<1000000000000000;i++);

because a for loop is still a Synchronous operation so /route1 will have to wait till /route2 ends因为for loop仍然是同步操作所以/route1将不得不等到/route2结束

Refer below Node.js Guides for more details:有关更多详细信息,请参阅下面的 Node.js 指南:

Blocking vs Non-Blocking 阻塞与非阻塞

The Node.js Event Loop Node.js 事件循环

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

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