javascript Node.js - Async.js:并行执行如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17137134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:13:11  来源:igfitidea点击:

Node.js - Async.js: how does parallel execution work?

javascriptnode.jsparallel-processingasync.js

提问by Danilo Aburto Vivians

I want to know how parallel execution works in async.js

我想知道在 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:

在上面的例子中,我希望获得输出:

function: 2

function: 1

功能:2

功能:1

but, the console throws the inverse, what is happening? thanks.

但是,控制台抛出了相反的结果,发生了什么?谢谢。

回答by Daniel

You get the answer you don't expect because asynclaunches function: 1first and it doesn't release control back to the event loop. You have no async functions in function: 1.

您会得到意想不到的答案,因为首先async启动function: 1并且它不会将控制权释放回事件循环。中没有异步函数function: 1

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.

Node.js 是一个单线程异步服务器。如果使用长时间运行的 CPU 任务阻塞事件循环,则在长时间运行的 CPU 任务完成之前不能调用其他函数。

Instead for a big for loop, try making http requests. For example...

对于大的 for 循环,尝试发出 http 请求。例如...

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);
      });
    }
]);

回答by Kaizo

Javascrit is single-threaded unless you use special libraries/modules. So when you are executing this code it will execute the first function and then the second one.

除非您使用特殊的库/模块,否则 Javascrit 是单线程的。因此,当您执行此代码时,它将执行第一个函数,然后执行第二个函数。

The only thing that async.parallel does is execute all the functions and wait for all the responses, and then execute the code in the callback.

async.parallel 唯一要做的就是执行所有函数并等待所有响应,然后执行回调中的代码。

Because all the code you used is synchronous the result will be a synchronous.

因为您使用的所有代码都是同步的,所以结果将是同步的。