JavaScript Multiple Callback Function
wouldn't this work:
function callback(f1, f2) {
f1();
f2();
}
As for passing arguments, be creative.
function1 = (callback1, callback2, callback3) => {
setTimeout(() => {
console.log("function 1 timed out!");
callback1(callback2, callback3);
}, 1500);
}
function2 = (callback1, callback2) => {
setTimeout(() => {
console.log("function 2 timed out!");
callback1(callback2);
}, 1500);
}
function3 = (callback1) => {
setTimeout(() => {
console.log("function 3 timed out!")
callback1()
}, 1500);
}
function4 = () => {
setTimeout(() => {
console.log("function 4 timed out!")
}, 1500);
}
function1(function2, function3, function4);
Just pass down the callbacks from the first function and execute each one, passing down the rest.
OUTPUT
function 1 timed out!
function 2 timed out!
function 3 timed out!
function 4 timed out!
To accomplish this, you need to pass the next callback into each function.
function printList(callback) {
// do your printList work
console.log('printList is done');
callback();
}
function updateDB(callback) {
// do your updateDB work
console.log('updateDB is done');
callback()
}
function getDistanceWithLatLong(callback) {
// do your getDistanceWithLatLong work
console.log('getDistanceWithLatLong is done');
callback();
}
function runSearchInOrder(callback) {
getDistanceWithLatLong(function() {
updateDB(function() {
printList(callback);
});
});
}
runSearchInOrder(function(){console.log('finished')});
This code outputs:
getDistanceWithLatLong is done
updateDB is done
printList is done
finished