What is the real advantage of using a CallBack and what is thread / multithread?

20

It has a lot of explanation of what is callback by the net and even a few sparse examples, but nothing that explains in practice and in detail a really important use (I did not find it).

I already understood a bit of how to use and even made my version of an example that I found on the net, however, the same can be replicated without using callback and work the same or even better

I'm trying to introduce myself to the concepts and standards of Node.js which is full of it: multithread, callback, asynchronism, etc., but as long as I do not really understand what a callback is for or what a thread is, I think I'll never learn Node .js for real.

I would like simple examples and / or some classic and indispensable example in Node.js since it is my focus.

Note : I studied programming only 7 months ago and until now I only moved on the client side, my journey to the back end is recent. This can be helpful in forging the answer.

    
asked by anonymous 02.01.2015 / 22:48

3 answers

20

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.

    
03.01.2015 / 00:49
6

What is the real advantage of using a CallBack?

The advantage is that you can define a parameter in a class that is actually a function. This exempts the programmer from a framework, for example, from writing this function, leaving it to a programmer. The framework only calls the function defined by the programmer without necessarily checking what this function does.

Although advantageous for flexibility and freedom, and the possibility of extending the functionality of an object, the approach by callbacks is somewhat permissive, and therefore dangerous, since it can make the programmer define a function that goes beyond aspects such as security and information responsibility.

What is Thread / Multithread?

Thread ( run thread thread ) #.

Multithread is the ability of a process to handle multiple threads, functionality claimed by Node .js , although the JavaScript programming language does not have this feature.

    
02.01.2015 / 23:23
5

Javascript is single-threaded

In and out of the browser (nodejs), javascript runs within a single line of execution (or Thread). Some languages allow you to create threads, but this is not the case for javascript.

For example:

var a = 1;
for (var i=0; i<100000000; i++) { a++; }

If this code takes 10 seconds to execute, the execution of any other instruction on the system will be interrupted for 10 seconds.

If in the browser this is not a good idea, on the server side (nodejs) it is even worse, since no other requests will be answered until the looping execution is finished.

Callback to solve the problem

To solve the above problem, the use of callback functions was invented. It is like this - I / O operations like file reading and writing, database access or server connections are very time-consuming, so in order to not lock the entire system in these situations, the solution found in javascript was the use of functions callback.

Callback functions are passed as parameter and calls when the operation terminates. For example, in nodejs, to read a file you use the following statement:

var fs = require('fs);
fs.readFile('c:\myfile.txt', function (err, data) {
  if (err) {
    console.log(err);
  }
  else {
    console.log(data);
  }
});

console.log('teste');

In the example above, the first line tries to read the file passed as parameter. Since file reading is a process that takes time (in computational cycles), the control is passed to the node's IO library (unit 'fs'), and execution continues to the next line, where the message' test 'on the console screen.

When the file is read or an error occurs (for example, file not found), the fs.readFile function will call the callback function that will display the error message or the contents of the file.

I hope I have helped.

    
04.01.2015 / 02:38