并行运行asynchronous代码

使用aync库,是否可以创build真正的asynchronous任务,而无需使用预先构build的asynchronousI / O函数?

例如,如果运行此代码,它将始终按顺序运行这些函数,因为node.js是“单线程的”。

var async = require('async'); async.parallel([ function(){ console.log('1') }, function(){ console.log('2') }, function(){ console.log('3') }, function(){ console.log('4') } ]); 

我们不应该阻止节点 – 是的 – 但node.js运行在单核上。 如果我们想利用其他内核,我们可以产生进程,并以这种方式使用asynchronous库。

除了集群模块之外,是否有其他核心上产生asynchronous进程的最佳实践方法?

好吧,我想出了一个好的解决scheme。 为了最简单的情况,我们使用核心模块'child_process'。 你甚至不需要运行npm install来使用这个模块,它是一个核心模块。

为了解决这个问题,我使用了这里的信息:

http://blog.carbonfive.com/2014/02/28/taking-advantage-of-multi-processor-environments-in-node-js/

https://nodejs.org/api/child_process.html

 //main.js var cp = require('child_process'); var async = require('async'); async.parallel([ function one(callback){ console.log('1'); var k = cp.fork('./doOther.js',['01']); k.once('message',function(msg){ console.log(msg); callback(); }); }, function two(callback){ console.log('2'); var k = cp.fork('./doOther.js',['02']); k.once('message',function(msg){ console.log(msg); callback(); }); }, function three(callback){ console.log('3'); var k = cp.fork('./doOther.js',['03']); k.once('message',function(msg){ console.log(msg); callback(); }); }, function four(callback){ console.log('4'); var k = cp.fork('./doOther.js',['04']); k.once('message',function(msg){ console.log(msg); callback(); }); } ],function(){ console.log('done.'); process.exit(0); }); 

一个单独的文件在同一个目录中:

 //doOther.js process.on('message', function(msg) { console.log('child process got message:', msg); }); setTimeout(function(){ process.send({ foo: process.argv[2] }); },1000); 

把这两个文件放在同一个目录下,然后离开你。 随意问任何问题。 我会回应。

以上可以简化为这样的东西:

  async.parallel([1,2,3,4].map(function(val){ return function(cb){ console.log(val); var k = cp.fork('./other-script.js',[val]); k.once('message',function(msg){ console.log(msg); cb(null, msg); }); }, }), function(err, results){ console.log('done.'); process.exit(0); });