I am making an Express app and I was going to use setTimeout to invalidate the access token used with a third party API after a set amount of time. I thought that it might not work, since async functions like setTimeout are pushed onto the event queue and don’t run until everything else is done running. The Express app (I’m assuming) is always running because it’s always listening for requests so I thought that since the program never finishes, the setTimeout would never run. But the setTimeout ran just fine and on time.
How come this is still possible? Is there non-JS stuff in the listening part of Express, or have I misunderstood async and the event queue?
Advertisement
Answer
The requests that Express serves all go through the event queue just like the setTimeout()
so they share the same event queue and can be interleaved just fine.
So, when an incoming request arrives on the Express server, some lower level TCP code inserts that incoming connection into the event queue. The next time Express finishes executing something, the nodejs interpreter goes back to the event queue and grabs the next event. That could be the next incoming request, it could be some intermediate asynchronous operation in servicing a request (such as a database query finishing) or it could be your setTimeout()
.
Events are generally served FIFO (first-in-first-out), though there are some priorities among different types of events that can effect ordering details when there are multiple different types of events in the queue waiting to run.
The Express app (I’m assuming) is always running because it’s always listening for requests so I thought that since the program never finishes, the setTimeout would never run. But the setTimeout ran just fine and on time.
“Always running”, in this case, just means that it is ready and waiting for an incoming request. Other things in the event queue (like a timer) are able to run just fine whenever the JS interpreter returns back to the event loop for the next event.