Use of callback to work with asynchronous javascript

1

Following the code below, is there a better way to call the sendEmail () method after receiving "success" in ajax called by the gravaVisita () method? Notice that I used callback as a solution to this problem.

There are 2 "js" files:

  • The first file has the gravaVisita () method that is called by the view:

    this.gravaVisita = function (visitado, visitante) {    
          if (visitado == visitante)
              return;
    
          dataBD.gravaVisita(visitado, visitante,
              function (data) {
                  if (data.statusRetorno == 200)
                      dataBD.enviaEmail();
              }
          );
    }
    
  • The second is responsible for making an ajax call to the "GravaVisita" action of the "AccountMVVM" controller

    function DataBD() {
        this.gravaVisita = function (visitado, visitante, callback) {
            var dataJson = {
                LoginFoiVisitado: visitado,
                LoginVisitou: visitante
            };
    
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "/site/apiPostForm/AccountMVVM/GravaVisita",
                data: dataJson,
                success: function (data) {
                    if (callback) callback(data);
                },
                error: function (error) { }
            });
         }
    }
    var dataBD = new DataBD();
    
  • asked by anonymous 23.05.2014 / 22:22

    1 answer

    2

    I think the code is already very good. I like the asynchrony!

    A modification to potentialize it (asynchrony), with advantages and disadvantages that I will discuss already, would move the status check ( data.statusRetorno == 200 ) to success , thus showing only the part what matters:

    ...
    success: function (data) {
        if (callback && data.statusRetorno == 200) callback();
    }
    ...
    

    Of course, the callback function would also be modified:

    ...
    dataBD.gravaVisita(visitado, visitante,
        function () { dataBD.enviaEmail(); }
    );
    ...
    
    The most obvious advantage is the leaner code, since the data parameter becomes expendable for callback , which in turn is only called when really necessary - in the case of absolute success (200). In this way, the dependency between the two functions (the success and the callback ) is minimal.

    The downside, and I believe that you have actually programmed it in your way precisely because of it, is precisely this minimal dependency; if your code of callback does not stop there, the next lines will not have access to the object data and its valuable (I suppose!) information.

    So if the changes improve or worsen your program, it's up to you to decide. I just hope it helped you reason: D

        
    23.05.2014 / 22:51