microwth
microwth

Reputation: 1066

NodeJs- does the Event Loop only handle I/O requests?

In general is an event loop only for IO ? and what exactly is an IO job? For example let's say that a request comes into NodeJs which is then making an outbound http request to an API to get some data while not blocking the user in the meantime.

Is that an IO job and how would NodeJs handle it? what if instead of the http request I wanted to asynchronously make a lengthy calculation and then return a value to the user? Is that handled by the event loop too despite being CPU bound?

Upvotes: 0

Views: 392

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

In general is an event loop only for IO ?

I wouldn't count timers (setTimeout, setInterval) and sheduling (setImmeadiate, process.nextTick) as IO but one could generally say that the events in the event loop are coming from the outside

and what exactly is an IO job?

That depends on the context you are talking about. Every program gets a certain Input by the user and generates a certain Output. In a terminal for example the input are your keypresses and the output is what is displayed. Whe talking about nodejs IO, one usually refer to network / file operations, or more generally: code not written in js.

For example let's say that a request comes into NodeJs which is then making an outbound http request to an API to get some data while not blocking the user in the meantime.

Is that an IO job and how would NodeJs handle it?

Nodejs would spawn a background thread that makes the request, the main process continues with other stuff in the meantime (continues with other events on the event queue). Then if the async request is done the background process pushes the result onto the event queue, the event loop will pull it from there and execute callbacks etc.

what if instead of the http request I wanted to asynchronously make a lengthy calculation and then return a value to the user?

You have to spawn another thread in nodejs, lengthy calculations are synchronous otherwise.

Is that handled by the event loop too despite being CPU bound?

Everything somewhen lands on the event loop, and everything gets executed on the CPU ...

Upvotes: 2

Related Questions