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

2

17

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.

Miosis answered 16/6, 2013 at 19:59 Comment(1)
The async library doesn't make a task/function asynchronous. It assumes the tasks are already asynchronous and simply helps you keep track of a group of them. And, neither of your tasks are asynchronous.Skeptic
D
22

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);
      });
    }
]);
Dulcie answered 16/6, 2013 at 20:5 Comment(2)
in this example, I'll be passing back two callbacks, so how does that work? shouldn't there be a single callback once both of these occur?Perdurable
This was just an example of making two requests at the same time. The output goes to console. If you want to collect the output you'll need a final function. Check out the async documentation for more details on the parallel method.Dulcie
V
8

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.

Violent answered 16/6, 2013 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.