What is a callback function?
“A callback is a function that is passed as an argument to another function”
Which is then invoked inside the outer function to complete some kind of routine or action.
Callbacks are also known as a higher-order function.
I am callback function
Why do we need Callback Functions?
What is a Callback Advantage?
Callbacks can help to make your code more maintainable if you use them well. They will also help us to:
Keep your code DRY (Do Not Repeat Yourself)
Implement better abstraction where you can have more generic functions like compute that can handle all sorts of functionalities (e.g., sum, product)
Improve code readability and maintainability.
How to create a Callback?
To understand what I’ve explained above, let me start with a simple example. We want to log a message to the console but it should be there after 3 seconds.
In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.
What are Asynchronous callbacks?
An asynchronous callback is a function that is passed as an argument to another function and gets invoked zero or multiple times after certain events happen.
It’s like when your friends tell you to call them back when you arrive at the restaurant. You coming to the restaurant is the “event” that triggers the callback. Something similar happens in the programming world. The event could be you click a button, a file is loaded into memory, and request to a server API, and so on.
First, you notice that we are using anonymous functions (in the previous example, we were passing the named functions such as sum and product). The callback passed to setInterval is triggered every second, and it prints tick. The second callback is called one after 5 seconds. It cancels the interval, so it just writes tick five times.
Callbacks are a way to make sure a particular code doesn’t execute until another has already finished.
The console.log(‘tick’) only gets executed when a second has passed.
The functions setInterval and setTimeout callbacks are very simple. They don’t provide any parameters on the callback functions. But, if we are reading from the file system or network, we can get the response as a callback parameter.
Callback as an Arrow Function
Benefit of Callback function
The benefit of using a callback function is that we can wait for the result of a previous function to call and then execute another function call.
In this example, we are going to use the setTimeout( ) method to mimic the program that takes time to execute, such as data coming from the server.