The biggest Javascript process is considered a single event. If you perform a long operation within this event the process may briefly stop the browser (or other software that uses ECMAScript), then the process will stop processing other events until it completes its operation and will probably freeze the browser. / p>
For example, if you use XMLHttpRequest
this way:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url_arquivo_grande', false); //false = síncrono
xhr.send(null);
alert(xhr.responseText);
alert('Outra tarefa...');//Isto iria demorar de aparecer e provavelmente o navegador irá congelar
The main browser process will get stuck until the server finishes sending the response to the client and the client (client in case it is the browser) processes this response.
So in XMLHttpRequest
we use AJAX
(Asynchronous Javascript and XML) which would be the asynchronous way of it, which would be something like:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url_arquivo_grande', true); //true = assincrono
xhr.onreadystachange = function () { alert(xhr.responseText); };
xhr.send(null);
alert('Outra tarefa...');//Isto não espera o ajax
You do not need to use callback
for everything, but if your code has a great chance of blocking / freezing other operations it is essential that you use asynchronous methods, or even setTimeout
.
What really leads us to callback
If the code is time-consuming (even if it is not XMLHttpRequest
), you should use setTimeout
, from this moment you no will not be able to use return ...
you will need to use callback
.
But it's like I said, there's no need to use callback at all, just where asynchronous events will be needed.
Example of necessity 1:
In this example we will try to use
return
, but when we use
setTimeout
,
return
finishes the process before
setTimeout
, in other words,
return
will return
0
, only after a < the variable will be with the value
1
, however
return
was processed before this:
function test() {
var a = 0;
setTimeout(function() {
//Código demorado
a = 1;
//Código demorado
}, 1);
return a;
}
console.log(test());//Irá retornar 0
With callback it is possible to capture the response of an "asynchronous" event:
function test(callback) {
var a = 0;
setTimeout(function() {
//Código demorado
a = 1;
//Código demorado
callback(a);
}, 1);
}
test(function (response) {
console.log(response);//Irá retornar "1"
});
Example of necessity 2:
In the following example I used XMLHttpRequest
asynchronous, because it prevents freezes, but I tried to capture responseText
, but since the answer is not ready the result will be an "empty string", null
or undefined
.
function ajax() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url_arquivo_grande', true);
xhr.send(null);
return xhr.responseText;
}
console.log(ajax());//Irá retornar null ou undefined
But if we use onreadystatechange
, we can wait for the response from the server, but it will not be possible to use return
, since the event is in another cycle / it is asynchronous, as in the example:
function ajax() {
var data = null;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url_arquivo_grande', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
data = xhr.responseText;
}
}
};
xhr.send(null);
return data;
}
console.log(ajax());//Irá retornar null
So the solution is to use callback:
function ajax(callback) {
var data = null;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url_arquivo_grande', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
callback(xhr.responseText);
}
}
};
xhr.send(null);
}
test(function (response) {
console.log(response);//Irá retornar "1"
});
Note, just because we have a setTimeout
, does not mean that it will be a guarantee against "crashes", so it follows a list of technologies developed to make the user experience better:
Note that Node.js is an asynchronous "server", unlike Apache that is synchronous. The likelihood of asynchronous servers performing better is very high and therefore it is so "quoted."
Difference from asynchronous to synchronous:
As previously explained, the reason for using callback in particular is because of asynchronous events, but if it was not possible to understand what is ASYNCHRONO, see an example of the difference between "synchrony" and "asynchrony" and the which we can not use asynchronous with return
:
The first (synchronous) drawing illustrates that a=1;
is in the queue and return a;
will only be executed after a=1;
, the disadvantage and if a=1;
is a time consuming process, so this can halt the main process, if it is not time-consuming, then yes you can use synchronous.
The image shows that a=1;
is in an asynchronous event (it can be ajax, setTimeout
, or other types), see that a=1;
was only delivered after return a;
, so this return is performed first and does not bring the required response, in the example it will bring the value 0
instead of 1
, so in this case callback will be needed.