Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel function calls in Node.js

I need to do a few independent database queries in Node.js. After all queries are executed, response should be sent. My first try looks like this:

templateData = {};

model.getA(function(result) {
    templateData.A = result;

    model.getB(function(result) {
        templateData.B = result;

        model.getC(function(result) {
            templateData.C = result;

            response.send('template', templateData);
        })
    })
});

Of course, this approach in Node.js is not good at all, because all functions are called sequentially and I'm loosing advantages of asynchronous programming pattern. I'm new to Node.js and it's still unclear to me how to call getA(), getB() and getC() in parallel and send response just after everything is finished. Is there some really simple and common way to achieve this?

like image 644
Peter Krejci Avatar asked Dec 26 '12 00:12

Peter Krejci


People also ask

Can NodeJS run parallel?

parallel is used in node. js, it is using process. nextTick() . And nextTick() allows you to avoid blocking the caller by deferring work onto a new stack so you can interleave cpu intensive tasks, etc.

Is NodeJS concurrent or parallel?

At a high level, Node. js falls into the category of concurrent computation. This is a direct result of the single-threaded event loop being the backbone of a Node. js application.

Is promise all parallel or series?

Depending on the “Task/CPU” it might run in parallel or concurrently or sequentially. In single-core CPU the promises would run concurrently and in multi-core CPU they can be executed (!) in parallel for CPU intensive tasks.


1 Answers

Use the async package: (npm install async)

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

https://github.com/caolan/async#parallel

Alternatively, you can use promises:

Q.spread(
    [ model.getA(), model.getB(), model.getC() ],
    function(a, b, c) {
        // set templateData
        return templateData;
    }
).then(...);

(assuming that the get*() methods return promises)

like image 168
SLaks Avatar answered Oct 19 '22 03:10

SLaks