Node.js - Async.js:并行执行如何工作? [英] Node.js - Async.js: how does parallel execution work?
问题描述
我想知道并行执行在async.js中是如何工作的
I want to know how parallel execution works in async.js
async = require('async')
async.parallel([
function(callback){
for (var i = 0; i < 1000000000; i++) /* Do nothing */;
console.log("function: 1")
},
function(callback){
console.log("function: 2")
}
]);
在上面的例子中,我希望获得输出:
In the above example, I expect obtain the output:
功能:2
function: 2
功能:1
但是,控制台抛出反转,发生了什么?谢谢。
but, the console throws the inverse, what is happening? thanks.
推荐答案
你得到了你不想要的答案,因为 async
首先启动函数:1
,它不会将控制权释放回事件循环。您在函数中没有异步函数:1
。
You get the answer you don't expect because async
launches function: 1
first and it doesn't release control back to the event loop. You have no async functions in function: 1
.
Node.js是一个单线程异步服务器。如果使用长时间运行的CPU任务阻止事件循环,则在长时间运行的CPU任务完成之前不能调用其他函数。
Node.js is a single-threaded asynchronous server. If you block the event loop with a long running CPU task then no other functions can be called until your long running CPU task finishes.
而不是大的for循环,请尝试发出http请求。例如......
Instead for a big for loop, try making http requests. For example...
async = require('async')
request = require('request')
async.parallel([
function(callback){
request("http://google.jp", function(err, response, body) {
if(err) { console.log(err); callback(true); return; }
console.log("function: 1")
callback(false);
});
},
function(callback){
request("http://google.com", function(err, response, body) {
if(err) { console.log(err); callback(true); return; }
console.log("function: 2")
callback(false);
});
}
]);
这篇关于Node.js - Async.js:并行执行如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!