2

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

1
  • Show some code plz.. From what you have said, I don't find any complexity. Some code sample should explain better.. Commented Nov 11, 2014 at 6:50

2 Answers 2

4

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.
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks. how can i call Q.all(promises) to do this process ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.