📜 ⬆️ ⬇️

Callback in javascript ... what a beast?

If you are not very well aware of what callbacks are and how to use them in JavaScript, now you have a chance to understand them and learn how to work with them.

image

Let's go straight to the point. A callback is a function that must be executed after another function completes. Hence the name, which, in the English spelling, can be represented as “call back”, although usually it is “callback”. Among the options for the translation of the word - "callback". In the Russian-language publications, allowing the use of jargon programmers, is very common tracing with the original name: "kollbek." If we do without jargon, then what we are talking about is called a “callback function”.

Going deeper, to explain the essence of callback functions, especially JavaScript, we can say that functions in JS are objects. Therefore, functions can take other functions as arguments and return them as results. Functions that work in this way are called higher order functions. Callbacks are usually called functions that are passed to other functions as arguments.

Why do we need callback functions?


Callbacks are needed for one very important reason: JavaScript is the language in which events play a huge role. This means that instead of waiting, say, the result of performing a function, stopping all other operations, the JavaScript program works by observing and responding to events.
')
Take a look at a simple example:

function first(){  console.log(1); } function second(){  console.log(2); } first(); second(); 

As you might expect, the first() function is executed first, and the second() function — second. Running this code causes the following to be displayed in the console:

 // 1 // 2 

So far, we hope everything is clear, but what if the function first() contains code that cannot be executed immediately? For example, is there an appeal to a certain API, and, first, you need to send a request, and then wait for an answer? In order to simulate this, we use the function setTimeout() , which is used in JavaScript to call other functions with a specified delay. We are going to postpone the function call for 500 milliseconds.

Here's what happened now:

 function first(){ //   setTimeout( function(){   console.log(1); }, 500 ); } function second(){ console.log(2); } first(); second(); 

For our purposes, the features of setTimeout() important right now. The main thing - note that the call console.log(1) will be executed with a delay.

This is what happens when you run this code:

 // 2 // 1 

In spite of the fact that the first() function was called first, the first thing that the second() function prints out to the log first.

This does not mean that JavaScript calls functions not in the order in which we place their calls in the code. The point is that the system goes to the execution of the function second() , without waiting for a response from the function first() .

In situations where, having called a certain function, it is impossible to be sure that the program will continue to work only after receiving a response from it, the use of callback functions is an approach that allows you to guarantee that a certain code fragment will be called only after then the other code will complete execution. For example, this happens all the time in any program that somehow interacts with the outside world — say, web services.

Create a callback function


Create your own callback function.

To get started, open the Chrome Developer Console ( Ctrl + Shift + J on Windows, or Cmd + Option + J on Mac) and type the following:

 function doHomework(subject) { alert(`Starting my ${subject} homework.`); } 

Here we declared the doHomework() function. This function accepts one variable - the name of the subject in which someone does homework. Call the function by typing the following in the console:

 doHomework('math'); //  : Starting my math homework. 

Now we add, as the second argument to the doHomework() function, the callback parameter that we will use to pass the doHomework() function to doHomework() . Now the code will look like this:

 function doHomework(subject, callback) { alert(`Starting my ${subject} homework.`); callback(); } 

Call the updated function as follows:

 doHomework('math', function() { alert('Finished my homework'); }); 

First, a message will appear with the text Starting my math homework. , then - with the text Finished my homework .

It is not necessary to create callback functions directly when calling functions to which they are passed. Such a function can be declared somewhere in the code:

 function doHomework(subject, callback) { alert(`Starting my ${subject} homework.`); callback(); } function alertFinished(){ alert('Finished my homework'); } doHomework('math', alertFinished); 

After calling the doHomework() function, everything will look exactly the same as in the previous example. The differences are only in how we work with the callback function.

As you can see, here, as an argument when calling the doHomework() function, we used the function name alertFinished() .

Callback functions in real projects


A special API is used for programmatic interaction with the popular social network Twitter. When executing calls to this API, we are forced to wait for a response, and only after receiving it, can we carry out what comes from Twitter some actions. Here is the material, which describes how to work with the Twitter API in the Node.js environment using the NPM twitter package.

Consider the code snippet from this material. We believe it is an excellent demonstration of the practical use of callback functions.

 T.get('search/tweets', params, function(err, data, response) { if(!err){   //      ,    Twitter } else {   console.log(err); } }) T.get() 

Is a function that makes a get request to the Twitter API. The function has three arguments. The first, 'search/tweets' , is the query route. Here we are going to search tweets. The second argument, params , is the search parameter. The third argument is an anonymous function, which is a callback function.

The callback function is very important here, because, before continuing to work, you need to wait for a response from the server. It is not known whether the appeal to the API will be successful, therefore, after sending search parameters along the search/tweet route using a get request, you have to wait. As soon as Twitter responds to the request, the callback function will be executed. If something went wrong, we get an error object ( err ) in it. If the request is processed normally, the err argument will have a value equivalent to false , which means, first, the if branch of the conditional operator will be executed, and secondly, it will be possible to expect that there will be some useful data in the response object, with which you can already do something.

Results


Hopefully, our story about the callback functions in JavaScript turned out to be useful to those who did not understand them very well. In fact, what we have said here is just the tip of the iceberg. But now, having understood the basics, you can expand and deepen your knowledge in this area.

Dear readers! If you are one of those who, before reading this material, had a bad idea of ​​what callback functions are in JS, tell me - has it become clearer? And if callbacks are common for you, please share your experience with newbies.

Source: https://habr.com/ru/post/330880/


All Articles