0

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.

1
  • 1
    DB 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. Commented Jul 15, 2015 at 20:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please point me to some sample code that handles this on a separate thread ?
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.)
Thanks, I figured it out. Just handle the request in the callback. I am using node-mssql by the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.