Meow
Meow

Reputation: 19111

What design pattern should I apply when checking multiple ajax request completion?

I have 3 ajax call in one function and checkAjaxCompletion which checks each ajax completion flag.

What the code below does is send multiple separate ajax calls and interval method checks completion flags to determine whether to proceed or keep interval. (I know clearInterval is not shown but the point is I want to use something other than interval)

Current code is:

function manyAjax() {

   setInterval( function() { checkAjaxCompletion(); } , 200);

   ajax1(); 

   ajax2();

   ajax3();

}

function ajax1() {
   //send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}

function ajax2() {
   //send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}

function ajax3() {
   //send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}

function checkAjaxCompletion() {

   if(ajax1_flag == 1 && ajax2_flag == 1 && ajax3_flag == 1) {
       //everything went success, do some process
   }
   else if(ajax1_flag == 2 || ajax2_flag == 2 || ajax3_flag == 2) {
       //some ajax failed, do some process
   }
   else {
      //all ajax have not been completed so keep interval i.e. do nothing here
   }
}

But I'm hesitating to depend on using interval function because calling it so often seem such waste of memory. There must be better way to do. I'm thinking if observer pattern can be applied here but would like to hear opinions.

Upvotes: 1

Views: 568

Answers (4)

T I
T I

Reputation: 9943

Okay my idea was to make your own object that can handle sending an array of requests, keep a history of each request and do what i'm gonna call 'postProccessing' on each response, here is a probably very dodgy bit of code to hopefully demonstrate what I am thinking.

var Ajax = function() {
    var request, callback, lst;

    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }

    request.onreadystatechange = handleResponse;

    this.history = [{}];

    this.send = function(args) {
        for (var i = 0; i < args.length; i++) {
            if (args.url) {
                request.open(args.type || 'GET', args.url);
            }
            request.send(args.data || null);
            callback = args.callback;
            lst++;
        }
    }

    function handleResponse() {
        var response = {
            url: '',
            success: true,
            data: 'blah'
        };
        history.push(response);
        if (postProccess()) {
            callback();
        }

    }

    function postProcess() {
        if (this.history[lst].success) {
            return true;
        } else {
            return false;
        }
    }
}

Upvotes: 1

6yang
6yang

Reputation: 9

// ajax callback
            this.ajaxCallback = function(){                          
                $.ajax({            
                        type: "POST",
                        url: ajax.url,
                        data: {key: value},
                        async   : !isAll,// false使用同步方式执行AJAX,true使用异步方式执行ajax
                        dataType: "json",
                        success: function(data){
                            if(data.status == 'successful'){                                
                                selfVal.parent().find('.msg').addClass('ok').html(msg.ok);
                            }else if(data.status == 'failed'){
                                checkRet = false;
                                selfVal.parent().find('.msg').removeClass('ok').html(msg.error);
                            }else{
                                checkRet = false;
                            }
                            return this;
                     }
                });                 
            }               
            return this;

Maybe you want to check your inputvalue callback ajax in your form; You can view my website Demo, hope help you. http://6yang.net/myjavascriptlib/regForm

Upvotes: 1

Jimmy Miller
Jimmy Miller

Reputation: 1319

Dustin Diaz does a great job with this example.

function Observer() {
  this.fns = [];
}

Observer.prototype = {
  subscribe : function(fn) {
    this.fns.push(fn);
  },

  unsubscribe : function(fn) {
    this.fns = this.fns.filter(
      function(el) {
        if ( el !== fn ) {
          return el;
        }
      }
    );
  },

  fire : function(o, thisObj) {
    var scope = thisObj || window;
    this.fns.forEach(
      function(el) {
        el.call(scope, o);
      }
    );
  }
};

The publisher:

var o = new Observer;
o.fire('here is my data');

The subscriber:

var fn = function() {
  // my callback stuff
};

o.subscribe(fn);

To unsubscribe:

var fn = function() {
  // my callback stuff
};

o.subscribe(fn);

Upvotes: 1

Chris Nash
Chris Nash

Reputation: 3061

It is observer-notifier, if you want to call it that - but each of your ajax calls will more than likely have a callback in javascript when they complete. Why not call checkAjaxCompletion() at the end of each of them, and do nothing if you're still waiting on others?

Upvotes: 2

Related Questions