user3658423
user3658423

Reputation: 1944

node.js how to multitask functions

I use node.js for my webserver. When a user requests a page I need to call 3 different functions each returning different set of data related to a user and display them in one page.

  1. User data
  2. User orders
  3. Computational data (similar items to purchase)

currently, I call function#1 and when the callback happens, I call function#2 and when the callback happens, finally function#3. After that I send the response.

Is there a way I can request all 3 functions at once/simultaneously, multitask and then have the result back to the response?

Thank you...

Upvotes: 2

Views: 4451

Answers (2)

null
null

Reputation: 7926

The correct answer in this case is to use async, like Yogesh Katri mentioned. It's pretty simple to use and read.

If you need some more flexibility I suggest you take a look at Q, which works with promise objects. This allows you to have a generic implementation for handling async calls across your code.

// Create for each task a _promise_, execute each of them in parallel 
// and let them `resolve` their promise in the callback while you're 
// waiting on the _main_ flow with the `Q.all` method.

var Q = require('q');

// Wrapper to create promises

function promiseMe(fn) {
   var defer = Q.defer();
   fn(defer);
   return defer.promise;
}

// Create a fake async task (via setTimeout)

function fakeTask(desc, delay, result) {
   return promiseMe(function(defer) {
     console.log('Executing task ' + desc + ' ...');

     setTimeout(function() {
       console.log('Done executing task ' + desc + '.');
       defer.resolve(result);
       }, delay);
     });  
}

// Create an array of promises for all our tasks

var promises = [
   fakeTask('user data', 2000, { user: 'hansch' }),
   fakeTask('user orders', 1000, [ { order: 1 }, { order: 2 } ]),
   fakeTask('something else', 3000, { magic: true })
];

console.log('Waiting for all tasks to complete ...');

// Tell Q to wait for all promises to resolve

Q.all(promises).then(function(result) {
   console.log('All done.');

   console.log('User data', result[0]);
   console.log('User orders', result[1]);
   console.log('Something else', result[2]);
});

Upvotes: 1

Yogesh Khatri
Yogesh Khatri

Reputation: 1210

Yes, you can do it in a very simple way using async(https://www.npmjs.org/package/async) module of nodejs.

Usign async.parallel(https://github.com/caolan/async#parallel), you can execute multiple functions asynchronously and get all the results in a array in final callback,
like this.. (e.g. from documentation)

async.parallel([
    function(callback){
        setTimeout(function(){
            callback(null, 'one');
        }, 200);
    },
    function(callback){
        setTimeout(function(){
            callback(null, 'two');
        }, 100);
    }
],
// optional callback
function(err, results){
    // the results array will equal ['one','two'] even though
    // the second function had a shorter timeout.
});

Upvotes: 4

Related Questions