Skip to content

Instantly share code, notes, and snippets.

@ponyjackal
Last active November 16, 2020 10:39
Show Gist options
  • Save ponyjackal/5f59d0b3bd910b27c95cf4422cbb27bd to your computer and use it in GitHub Desktop.
Save ponyjackal/5f59d0b3bd910b27c95cf4422cbb27bd to your computer and use it in GitHub Desktop.
Callback in Javascript
Also known as the oldest way to handle asynchronous data, callbacks allow us to inject a function into an asynchronous execution so that we can control the result(s) when they are available. In a very indirect way, it's as if we're sending a "spy" who will inform us when something happens within the call we are executing.
We'll create a simple example to get started, a function that returns a new Date():
function getNewDate() {
return new Date();
}
const result = getNewDate();
console.log(result);
In this case, we save the result value in the variable result, print it on the screen and everything works as expected, but if this information happens to be within a call to an endpoint, timer, or some other execution that is not immediate, what happens?
Let's simulate the same case, but now the getNewDate function will only return the value after 4 seconds:
function getNewDate() {
setTimeout(function () {
return new Date();
}, 4000);
}
const result = getNewDate();
console.log(result); // undefined
When executed, we receive undefined as a result of the variable result. This is because the value returned by the getNewDate function is executed 4 seconds later, and our result variable expects the value at execution time, that is, we have to get this value ONLY when it is available, in case otherwise we will not be able to manipulate or store this value.
The solution for this case is quite simple, let's pass a function that is outside the scope of the getNewDate function to receive the real value that we want to manipulate, in this case, new Date ().
function getNewDate(callback) {
setTimeout(function () {
callback(new Date());
}, 4000);
}
function getPayload(payload) {
console.log(`The date is: ${payload}`);
}
getNewDate(getPayload);
To manipulate the result data of the getNewDate function, I created a function calledgetPayload, this is sent as a parameter to our main function that instead of returning the value as before, now executes the callback function passing the value of result as a parameter, like this the getPayload function is executed only when the value is available to be captured, simulating a" wait "within the execution. The function getPayload in turn only receives the payload that contains the result of the execution and prints on the screen: 🥳.
Callbacks are just the starting point, in the next article in this series we'll see how to work using Promises which, in addition to a better interface, has a couple of API's to better handle our asynchronous cases.
See you at the next one!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment