Use of callback to work with asynchronous javascript

Asked

Viewed 174 times

1

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

Are 2 files "js":

  1. The first file has the Windows() write method which 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();
              }
          );
    }
    
  2. 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();
    

1 answer

2

I believe the code is already very good. I liked the asynchrony!

A modification in the sense of potentiating it (asynchrony), with advantages and disadvantages that I will already discuss, would be to move the status check (data.statusRetorno == 200) to the success, thus showing only the part that 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 thinner code, since the parameter data becomes expendable for the callback, which in turn is only called when really necessary - in the case of absolute success (200). Thus, the dependence between the two functions (the success and that of callback) is minimal.

The downside, and I believe that you actually programmed in your own way precisely because of it, is just this minimal dependency; if your code callback does not stop there, the next lines will not have access to the object data and their 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 to reason :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.