问题
I know that NodeJS Event Loop collects Tasks from Event Queue and transfers control to the callback of the Task. When the task is completed, the Task transfers control from Event Loop.
Therefore, I think that actually returning the callback is an Event Loop that has received control right from the Task.
Is this the right idea?
Also, if the assumption is correct about the blocking phenomenon that can occur in the Event Loop, if there is a delayed asynchronous task, can the event loop process other tasks while waiting for control to be returned from the task?
Or is that assumption incorrect, so the Event Loop doesn't work until the delayed asynchronous task is completed?
In the case of async await, I wonder if await stops the Event Loop.
回答1:
You can think of the Event Loop as an actual loop, something like:
let event_queue = [compiled_toplevel_code];
while (true) {
if (event_queue.length === 0) {
sleepUntilWokenUp();
}
if (event_queue.length > 0) {
let callback = event_queue.shift();
callback();
}
}
where sleepUntilWokenUp()
is a special function that suspends the current thread until another thread sends some signal to wake it up. Async operations (like file system or network access) are handled by such other threads. When they have a callback ready to execute, they will enqueue it and then send the appropriate wake-up signal.
You can imagine setImmediate(callback)
as being implemented as event_queue.push(callback)
.
"Transferring control" from the event loop to a callback simply means calling the callback; "returning control" to the event loop simply means that the callback function returns.
Long-running "async" tasks always decompose into snippets that run on the main thread, schedule some work to be done (typically on another thread), then return. Once the requested task has been completed in the background, their corresponding callback is enqueued. Even "synchronous" calls with await
are just syntactic sugar for splitting the function in two halves such that the first half runs to completion, and the second half is pushed onto the event_queue
when the awaited task has completed.
The full situation in reality is somewhat more complicated (and described in detail in the Node documentation) with a few different queues for different kinds of things, but the above describes the general idea.
来源:https://stackoverflow.com/questions/65870887/what-is-the-exact-handling-of-the-nodejs-event-loop