任务完成和回调函数执行之间是否有延迟?

Is there a delay between task completion and callback function execution?

我正在学习 Node.js 和一些 javascript。我阅读了一些想法,例如队列和执行堆栈。

我正在尝试计算完成 websocket 请求所用的时间。一个非常典型的发射形式是:


microtime1  = getTimeNow;

socket.emit("message","data", function (error, data) {
    // calculate time taken by using microtime module by getting updated time and calculating difference.
       microtime2  = getTimeNow;
       time = microtime2 - microtime1;

})

如果我要发送多条消息,我可以依靠回调立即执行,还是可以在队列中暂停并且回调不会执行。

换句话说,回调只会在它进入堆栈时才被调用,还是在等待在队列中被提取时被执行?

希望,我能够解释我的问题。

换句话说,回调只会在它进入堆栈后才被调用,还是在等待在队列中被提取时被执行?

回调在它正在等待的事件解决后执行。

所以回调应该工作得很好,但是有一个警告。因为 node-js 是单线程的,你可能有另一个进程阻塞了主线程。

例如,执行的简单视图可能如下所示。处理完一个事件,之后再处理一个。

然而,实际上它可能看起来更像这样

单线程只针对主线程,IO操作等在另一个专用线程上完成,完成后会通知主线程,然后回调

如果您的主线程在等待网络操作完成时变得繁忙,则会出现此问题

虽然这很难预测,但取决于应用程序的其余部分在做什么。如果您的应用没有做任何其他事情,这可能不是问题。但是,恕我直言,更好的方法是进行数百或数千次调用,并允许获得一个平均值,这将解释导致增量差异的其他可能原因。


来自 c-sharpcorner.com

的额外数据

The above diagram shows the execution process of Node.js. Let's understand it step by step.

Step 1

Whenever a request comes to Node.js API, that incoming request is added to the event queue. This is because Node.js can't handle multiple requests simultaneously. The first time, the incoming request is added to the event queue.

Step 2

Now, you can see in the diagram that one loop is there which always checks if any event or request is available in event queue or not. If any requests are there, then according to the "First Come, First Served" property of queue, the requests will be served.

Step 3

This Node.js event loop is single threaded and performs non blocking i/o tasks, so it sends requests to C++ internal thread pool where lots of threads can be run. This C++ internal thread pool is the part of event loop developed in Libuv. This can handle multiple requests. Now, event loop checks again and again if any event is there in the Event Queue. If there is any, then it serves to the thread pool if the blocking process is there.

Step 4

Now, the internal thread pool handles a lot of requests, like database request, file request, and many more.

Step 5

Whenever any thread completes that task, the callback function calls and sends the response back to the event loop.

Step 6

Now, event loop sends back the response to the client whose request is completed.