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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad