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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
alf
  • 681
  • 1
  • 8
  • 19
  • 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. – tilleryj Apr 23 '13 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? – alf Apr 23 '13 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. – alf Apr 23 '13 at 20:28

2 Answers2

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

tilleryj
  • 14,259
  • 3
  • 23
  • 22
  • 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? – alf Apr 23 '13 at 21:06
  • No. They will be called in the order in which the queries return. – tilleryj Apr 23 '13 at 21:30
  • 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? – alf Apr 23 '13 at 21:37
  • 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: http://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback – tilleryj Apr 23 '13 at 21:53
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.

Deathspike
  • 8,582
  • 6
  • 44
  • 82