Green Files

What is callback?

Day: 05/31/2022 - Time: 15:14:24

Callback is a function that is used as "callback". It is typically passed as an argument to another function and/or called when an event occurs, or when a piece of code receives a response it was expecting.

This is very common in client and server side javascript (NodeJS) but not only. The callback function is often asynchronous in that it is called as a consequence of other code running in the background. The big advantage is that the computer can process other processes while the answer doesn't arrive, so it doesn't have to stop everything waiting for that answer.

A classic example is an event listener that calls a function when the event happens:

function callback(e) { alert('Something Happened' + e.type); } window.addEventListener('click', callback);

This callback will be called when you click on the window. Until that happens, the processor will process other things that happen in the application.

Another example is an ajax call, which makes a request to the server and runs the function when it receives the response.

This function is a "callback" function. In the example below I called it myCallBack.

function myCallBack(returnhtml) { $("#result").html(returnhtml); $("#loadingimg").hide(); } $(document).ready(function (e) { $.ajax({ url: form_url, type: form_method, data: form_data, cache: false, success: myCallBack }); });

Yet another example is an animation that calls the callback at the end of the animation being complete:

function completa() { alert('This alert is inside the "callback" function'); } $('div').animate({ 'height': '200px' }, { duration: 2000, complete: complete });

Yet another example, to try to clarify more after another question on the subject arises.

I'll make an analogy between synchronous code and asynchronous code.
Imagining this situation:

Problem:

How to transform a number into string format, with a decimal part too long that must be converted into dollars, and check if a given customer is entitled to a discount.

Synchronous solution:

To solve this problem synchronously, we need to know the initial value and the exchange rate before starting the calculation.

This is not always so, but for the example let's assume we know the following:

var valueInitial = "1003,087293487"; var ClientDiscount = "5%"; var exchange = 1.1158; // 1 EUR = 1.11580USD

So we can do the transformation in a simple way:

var inicialValueInNumerals = Number(valueInitial.replace(',', '.')); var ValueWithDiscount = inicialValueInNumerals - (inicialValueInNumerals * parseFloat(ClientDiscount) / 100); var DolarValue = ValueWithDiscount * exchange; var totalTwoDecimais = DolarValue.toFixed(2);

So the result is obtained with synchronous steps, and gives 1063.28

Asynchronous solution:

Now imagine that we need to do the same thing, but we don't have all the information available, because the exchange rates change constantly, we can't have the discount available to all possible customers, and not even the initial price because we have to ask our supplier first.

How to make?

In this case we have to do the asynchronous thing, that is, running part of the code, wait for answers, run another piece and wait for another answer, etc...

We can say that when we ask something to an external service we probably make an ajax request. And now we need a tool to get the response, that's where callbacks come into play.

When I send a question to an external service I have to tell them how they should contact/inform me with the result. A common way is to send a function with the request so that it runs when the response arrives.

Send a function with the request so that it is run when the response arrives

If I send a function to a setTimeout, I tell setTimeout what code to run when the time is up. This function can have the name we want, but its functionality, its type is callback:

var doSomething = function(){ alert('Time expired'); } setTimeout(doSomething, 2000);

Returning to the account example:

To do the previous calculation with asynchronous logic we have to chain things together and depend on functions that are being called with waiting times between them. So we have to chain everything, for example like this:

askPriceSupplier(Productnumber, function(Supplieranswer) { var inicialValueInNumerals = Number(Supplieranswer.replace(',', '.')); askDiscount(clientNumber, function(ClientDiscount) { var valueDiscountApplied = inicialValueInNumerals - (inicialValueInNumerals * parseFloat(clientDiscount) / 100); AskExchange('USD', function(dolarValue) { var dolarValue = valueDiscountApplied * dolarValue; var totalTwoDecimais = dolarValue.toFixed(2); // !! Now we have the result!! alert(totalTwoDecimais + 'USD'); }) }) })

This chaining of functions is necessary because each callback will be called when the external service wants it. For example, the function orderPrecoAoSupplier receives two arguments: the product number and a function. As I know that what I will receive is the price of the product, I already put this as the variable name, to make it easier to read. This function, which I now request, is a callback, a mechanism for the external service to be able to return what I need.

References:

https://pt.stackoverflow.com/questions/27177/o-que-%c3%a9-callback

GO UP
GO TO INDEX