如何并行运行所有功能

How to run all functions in parallel

本文关键字:运行 功能 并行 何并行      更新时间:2023-09-26

我正在张贴下面的一段代码,这是"非异步函数"

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!")
}

如果我们运行上面的例子,这应该是好的,c()函数,将不得不等待,直到a()和b()函数将完成工作。我期待所有的功能应该并行运行(多线程(异步)函数)。有谁可以帮助我如何使用nodejs实现它

使用承诺。all或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')});

就像评论中提到的那样,您可以使用child_processcluster.fork。下面是一个简单的child_process.spawn实现:

(如果您不想使用eval,那么将这些函数写在单独的文件中并调用它们)

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')