I have been trying to figure out the Callback function feature in Javascript for a while without any success. I probably have the code messed up, however I am not getting any Javascript errors, so I supposed the syntax is somewhat correct.
Basically, I am looking for the getDistanceWithLatLong() function to end before the updateDB() begins, and then make sure that ends before the printList() function begins.
I have it working with a hardcoded "setTimeout" call on the functions, but I am overcompensating and forcing users to wait longer without a need if the Callback stuff would work.
Any suggestions? Below is the code:
function runSearchInOrder(callback) {
getDistanceWithLatLong(function() {
updateDB(function() {
printList(callback);
});
});
}
An output can only have a single callback function.
As long as the callback code is purely sync than no two functions can execute parallel.
When using callbacks, you're required to put dependent program logic that is to be executed after an asynchronous operation has completed inside a callback. When you combine multiple such calls, you end up with deeply nested code. Deeply nested callbacks in JavaScript code.
We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node. js. It allows us to return a value from an asynchronous function like synchronous functions.
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
wouldn't this work:
function callback(f1, f2) {
f1();
f2();
}
As for passing arguments, be creative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With