I have got 2 ajax requests being fired on one of my pages, and I need to wait for both of them to load before displaying data to the user. What is the best way for managing this?
The ajax requests are sent from 2 seperate classes which expose a MakeRequest(successCallback, failedCallback) method, as im开发者_运维知识库 sure you can tell the relevant callback is invoked when the ajax completes.
These are both invoked within a controller (using knockoutjs), here is an example:
// Some JS File
function SomeController(ajaxService1, ajaxService2) {
    this.model = ...
    this.bothAjaxRequestsComplete = function() {
        ... Do something on view
    };
    this.invokeFirstAjax = function() {
        ajaxService1.MakeRequest(firstAjaxSuccess, firstAjaxFailed);
    };
    this.invokeSecondAjax = function() {
        ajaxService2.MakeRequest(secondAjaxSuccess, secondAjaxFailed);
    };
    var firstAjaxSuccess = function(data) {
        ... Do something on model
    };
    var secondAjaxSuccess = function(data) {
        ... Do something on model
    };
    var firstAjaxFailed = function(...) {...}
    var secondAjaxFailed = function(...) {...}
}
var someController = new SomeController();
$(document).ready(function(){
    someController.invokeFirstAjax();
    someController.invokeSecondAjax();
});
I've found using a "deferred" works pretty nicely for this kind of stuff. They allow you to easily define a list of actions that should execute, and a callback / list of callbacks.
I believe they introduced a jQuery deferred object in jQuery 1.5
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论