IsmaH IsmaH - 5 months ago 5
Node.js Question

NodeJS - Send multiple requests and process all responses in one callback

I'm trying to find a way to send multiple requests (using Express) and process all the response in one function.

Here's my code :

// In router.js
app.get('/api/FIRST_PATH', CALLBACK_FUNCTION_A );

// In CALLBACK_FUNCTION_A file :
module.exports = function (req, response) {
CALLBACK_FUNCTION_TO_SERVICE_A();
CALLBACK_FUNCTION_TO_SERVICE_B();
CALLBACK_FUNCTION_TO_SERVICE_C();
}


My problem is to send the requests CALLBACK_FUNCTION_TO_SERVICE_A, CALLBACK_FUNCTION_TO_SERVICE_B and CALLBACK_FUNCTION_TO_SERVICE_C and then retrieve all the results in another function to process them.

Any help would be greatly appreciated.

Answer

You can learn more about the new js standard and use Promise.

// In CALLBACK_FUNCTION_A file :
module.exports = function (req, response) {
   var promises = [CALLBACK_FUNCTION_TO_SERVICE_A(), 
      CALLBACK_FUNCTION_TO_SERVICE_B(),
      CALLBACK_FUNCTION_TO_SERVICE_C()];

   Promise.all(promises).then( function(results) {
       //results is an array
       //results[0] contains the result of A, and so on
   });
}

Of course CALLBACK_FUNCTION_TO_SERVICE_A() and such need to return Promise objects. You form a function like this:

function asyncFunction(callback) {
   //...
   callback(result);
}

You can create a Promise like this:

var p = new Promise(asyncFunction);

It'll start running the function, and supports the Promise interface.

So for example, either use request-promise or you can do something like:

function CALLBACK_FUNCTION_TO_SERVICE_A() {
   var worker = function(callback) {
       app.get('/api/FIRST_PATH', callback);
   };

   return new Promise(worker);
}

You can read more about Promise and how to also easily handle errors.