async parallel of API call with callback in node.js

Ad

I need to wait for tasks of two API callback functions and when tasks are done I would like to receive a callback so I can use data from both functions.

I would like the function will be parallel executed ... I read a lot of questions about async.parallel but I can't find a way to use these functions with async.

Of course async is only an example, any other way will be fine if it works.

I'm sorry for my bad english, I hope the code is easier to understand.

Thank you

var dataFunctionA = "";
var dataFunctionB = "";

var callbackFunctionA = function(err, response, data) {
  // do some work with data
  dataFunctionA = "Hello";
}

var callbackFunctionB = function(err, response, data) {
  // do some work with data
  dataFunctionB = " World!";
}

function printHelloWorld(){
   console.write(dataFunctionA + dataFunctionB);
}


APIClient.functionA(paramA, callbackFunctionA);

APIClient.functionB(paramB, callbackFunctionB);

// need to wait for the two callbacks
printHelloWorld();

Ad

Answer

Ad

If you don't want to use promises you could do something like:

var dataFunctionA = "";
var dataFunctionB = "";
var dataFunctionCount = 2;

function checkDone() {
  dataFunctionCount--;
  if(dataFunctionCount === 0) {
// need to wait for the two callbacks
printHelloWorld();  
  }
}

var callbackFunctionA = function(err, response, data) {
  // do some work with data
  dataFunctionA = "Hello";
  checkDone();
}

var callbackFunctionB = function(err, response, data) {
  // do some work with data
  dataFunctionB = " World!";
  checkDone();
}

function printHelloWorld(){
   console.write(dataFunctionA + dataFunctionB);
}

APIClient.functionA(paramA, callbackFunctionA);

APIClient.functionB(paramB, callbackFunctionB);

Ad
source: stackoverflow.com
Ad