开发者

Good pattern for waiting for multiple ajax results?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜