I am re-writing a c# server, and I would like to use an event driven model. My server needs to make complex database queries that may take some time to complete. How does this fit in with the event-driven model where I would have a single event loop processing all requests? I don't want to freeze the loop as I am waiting for a DB response.
Asked
Active
Viewed 1,916 times
0
-
1DB work in node.js is typically done asynchronously, so it will not freeze the loop, it will instead continue. This is usually the default behavior, so all you have to do to use it is correctly use callbacks. – Kevin B Jul 15 '15 at 20:04
1 Answers
3
I assume since you know about the event loop, you know how it works, but just in case, I'll leave this here.
When you send a query to the database, node.js will do so either over http, or some other protocol, this connection is usually handled on a separate thread. Once the request is sent, the code continues on and the callstack gets cleared, allowing the event loop to continue. Once a response is received, a function is injected into the callback queue, which gets processed when it's next in line and the event loop runs (and the event loop only runs when the call stack is empty, see video.)
As long as everything you do is asynchronous, you won't freeze the event loop.

Kevin B
- 94,570
- 16
- 163
- 180
-
Can you please point me to some sample code that handles this on a separate thread ? – Jacko Jul 16 '15 at 20:46
-
What db driver(module, etc) are you using?The separate thread i was referring to is usually on a separate server entirely (the database server.) – Kevin B Jul 16 '15 at 20:46
-
Thanks, I figured it out. Just handle the request in the callback. I am using node-mssql by the way. – Jacko Jul 16 '15 at 21:21