0

I have three functions. Just like the sample given below.

function1 {

  // Do some validation

}
function2 {

 // Do some read and write operations in DB

}
function3 {

 // Do some parallel task

}

How can I execute all the three functions parallel in nodejs. Thanks in advance.

user87267867
  • 1,409
  • 3
  • 18
  • 25
  • 1
    Possible duplicate http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js – sbarow Aug 14 '13 at 07:14
  • Take a look at [this](http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js) – NREZ Aug 14 '13 at 07:14

2 Answers2

3

You can use fork, as comments above suggest, or easier still use the async package from caolan.

Steve
  • 8,469
  • 1
  • 26
  • 37
1

It depends on what the functions do.

If they all use asynchronous I/O, you can simply call them so each can start that I/O, which will run in parallel.

function1();
function2();
function3();

Note: If you need to coordinate their completions, then you'll want to look into flow control libraries such as async or q.

But, if any of them are synchronous, then it gets trickier. You'll need to introduce asynchronous I/O around each of them. This can possibly be done through clusters or child_process to start multiple node processes.

But, it can't be done in JavaScript alone. JavaScript is still single-threaded with Node, so synchronous tasks will block other JavaScript code from executing. Asynchronous I/O is possible only through native C/C++ binaries using libuv.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199