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

本秂侑毒 提交于 2019-12-20 09:55:56

问题


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:

function: 2

function: 1

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


回答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 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.

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



回答2:


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.

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.

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



来源:https://stackoverflow.com/questions/17137134/node-js-async-js-how-does-parallel-execution-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!