0

I am posting a below piece of code which is "Not async functions"

var flag = false;
function a() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log("first fun finished!");
    flag = true;
};

function b() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log("second fun finished!");
};

function c() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log(a)
};
a();
b();
console.log("This should be good");
if (flag) { //Should wait for this value before c() is called
    c();
    console.log("third fun finished!")
}

If we will run above example, This should be good and c() function, will have to wait untill a() and b() functions will finish to work. I am expecting all the functions should run parrallel (multithread (async) functions). Can any one help me how can I achieve it using nodejs

user4324324
  • 559
  • 3
  • 7
  • 25
  • 2
    the only way this would be possible is through child processes (because they run in separate threads) – Kevin B Jul 07 '15 at 18:53
  • @KevinB can you help me with any pseudo? – user4324324 Jul 07 '15 at 19:00
  • I could whip something up, but, i've never actually used child processes so it'd likely be better to find a guide somewhere. The gist of it is, you wrap each separate action into it's own "application", and you use a node module (built-in) to spawn a process that runs those applications in parallel until they end. – Kevin B Jul 07 '15 at 19:01
  • It's essentially the same thing as executing a cmd line command from node.js, and waiting for it to complete. https://nodejs.org/api/child_process.html – Kevin B Jul 07 '15 at 19:03
  • possible duplicate of [Parallel JavaScript Code](http://stackoverflow.com/questions/3897625/parallel-javascript-code) – sergdenisov Jul 07 '15 at 19:35

2 Answers2

0

Use Promise.all or Promise.join.

var Promise = require('bluebird');
return Promise.join(Promise.resolve().then(a),
                    Promise.resolve().then(b),
                    Promise.resolve().then(c),
                    function(){console.log('complete')});
Chuan
  • 411
  • 5
  • 9
0

Like it's mentioned in comments you can use child_process or cluster.fork. Here is a simple child_process.spawn implementation:

(If you don't want to use eval then write those functions in separate files and call them)

var spawn = require('child_process').spawn
...

spawn('node',['-e', '('+a.toString()+')()']) // send the function as string and evaluate in node
  .stdout.on('data', console.log.bind(console))
  .on('close',function(){
    //call c() when a() ended
    c()
  })
  .setEncoding('utf8')

spawn('node',['-e', '('+b.toString()+')()'])
  .stdout.on('data', console.log.bind(console))
  .setEncoding('utf8')
hassansin
  • 16,918
  • 3
  • 43
  • 49