What is callback?
Basics: Callback is a function that is executed after another function has completed.
In JavaScript, every function is an object. Therefore, each function can use other functions as arguments and can also be the result returned by other functions. Such functions are called higher-order functions . Any function passed as an argument is called a callback function
Let’s take a look at some examples in this article to have a clearer view of the callback function
Why is Callback needed?
Because JavaScript is event-oriented language. That means that instead of waiting for a response, JavaScript always executes listening for events. See the example below:
1 2 3 4 5 6 7 8 9 | function first(){ console.log(1); } function second(){ console.log(2); } first(); second(); |
The first
function is tested first and then the second
function.
1 2 3 | // 1 // 2 |
But what if the first
function contained blocks of code that were not immediately executed? For example, we need to wait for a response when sending an API request. To simulate this action we can use setTimeout
– a JavaScript function called after a certain amount of time. We will delay 500 milliseconds to simulate an API request.
1 2 3 4 5 6 7 8 9 10 11 12 | function first(){ // Simulate a code delay setTimeout( function(){ console.log(1); }, 500 ); } function second(){ console.log(2); } first(); second(); |
1 2 3 4 5 | first(); second(); // 2 // 1 |
Although the function first()
is called first, its result is displayed after the result of the function second()
.
From this it can be seen that JavaScript did not execute functions in the order we expected, more specifically, it did not wait for the response from the first()
function before executing the second()
function.
Because we cannot call a function after another and hope they are executed in the desired sequence. Callback is one way to make sure not to execute blocks until another block has been completed.
Create a Callback
Open Chrome Developer Console (Windows: Ctrl + Shift + J) (Mac: Cmd + Option + J) and enter the following command
1 2 3 4 | function doHomework(subject) { alert(`Starting my ${subject} homework.`); } |
For the above example, we have the doHomework
function with a subject argument passed.
1 2 3 | doHomework('math'); // Alerts: Starting my math homework. |
Now let’s try passing a function callback as argument to the doHomework()
function
1 2 3 4 5 6 7 8 9 | function doHomework(subject, callback) { alert(`Starting my ${subject} homework.`); callback(); } doHomework('math', function() { alert('Finished my homework'); }); |
As you can see, if we execute that line of code on the console, there will be 2 alert messages displayed showing starting homework
alert and finished homework
alert.
However, the function callback does not always have to be defined right after the function call. They can be defined anywhere as follows:
1 2 3 4 5 6 7 8 9 | function doHomework(subject, callback) { alert(`Starting my ${subject} homework.`); callback(); } function alertFinished(){ alert('Finished my homework'); } doHomework('math', alertFinished); |
The result of the above example is identical to the previous one, but we declare it a bit different. As you can see, we passed the alertFinished
function as an argument to the doHomework()
function doHomework()
Practical examples
1 2 3 4 5 6 7 8 | T.get('search/tweets', params, function(err, data, response) { if(!err){ // This is where the magic will happen } else { console.log(err); } }) |
T.get
sends an API request to the server- There are three params in the request:
search/tweets
– the path of the request,params
– the search parameters and finally an anonymous callback function.
The callback function is here to wait for a response from the server and then decide what action to take next. We do not know if the API request was successful or not. By using if()
to check the status of the request then report an error or execute the desired code.
The above article I have introduced you to the concept of callback and how it is used. Have a nice day!
JavaScript Reference : What the heck is a Callback?