0

For an application where each request may take a second or two, is it possible to only process a piece of operative code on each iteration of the event loop? For example:

function foo()
{
    ...operative code...
    ...start processing the next event here...
    ...continue with foo() here....
}

Would it be something like this?

function foo()
{
    ...operative code...
    process.nextTick(function() {
        ...continue with foo() here...
    });
}

And if that is the way to do it, does Node automatically start processing whichever event is next in the queue?

3
  • Is your operative code IO based? Usually when I have something that is running for a second or two it's mostly IO time. If this is the case, then node will handle concurrency automatically as it's IO model is non-blocking. Commented Apr 23, 2013 at 20:24
  • @tilleryj Assuming it isn't IO based, is there a way to jump to the next event and come back later to continue processing? Commented Apr 23, 2013 at 20:26
  • @tilleryj And I realize it would take A LOT of code for a non IO function to take more than a second. But I'm really just trying to get a feel for how the event loop works, and how much control I have over it. Commented Apr 23, 2013 at 20:28

2 Answers 2

1

If the time is spent in IO, node's non-blocking model will automatically handle concurrency.

If it's not spent in IO, then you're right in using process.nextTick to defer the execution of your code so that other requests have a change to be handled. Here is a good writeup:

http://howtonode.org/understanding-process-next-tick

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

4 Comments

Thank you. Also, are all of node's IO calls sequential? Say I have something like, db.query(query, callback1); db.query(anotherQuery, callback2);. Will callback1 always be called first?
No. They will be called in the order in which the queries return.
But what if both calls involve writing to disk? Maybe something like this would better illustrate my question, file.write(somethingLong,callback1); file.write(somethingShort,callback2);. Wouldn't callback1 always get called first in this case?
Not sure. However the docs for fs.write say you shouldn't call write more than once on the same file without waiting for a callback: nodejs.org/api/…
1

Your assumption is correct, you should be dividing the work into smaller blocks of execution and schedule the next block with process.nextTick. All the other scheduled events that need to be executed at the next tick will be handled prior to your block of required execution.

Comments

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.