How to accumulate data from various AJAX calls?

Besides making synchronous AJAX calls, if you can and think it's appropriate, what's the best way to handle something like this?

var A = getDataFromServerWithAJAXCall(whatever);
var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A);
var C = getMoreDataFromServerWithAJAXCall(whatever2);

processAllDataAndShowResult(A,B,C);

Provided that I can pass callbacks for these functions, I know that I can use closure and lambda to do this work as follows:

var A,B,C;

getDataFromServerWithAJAXCall(whatever, function(AJAXResult) {
    A= AJAXResult;
    getDataFromServerWithAJAXCallThatDependsOnPreviousData(A, function(AJAXResult2) {
        B= AJAXResult2;
        processAllDataAndShowResult(A,B,C);
    });
});
getMoreDataFromServerWithAJAXCall(whatever2, function(AJAXResult) {
    C= AJAXResult;
    processAllDataAndShowResult(A,B,C);
});

function processAllDataAndShowResult(A,B,C) {
    if(A && B && C) {
        //Do stuff
    }
}

But for me it does not seem right or clean. So is there a better way, or at least a cleaner way to do the same, or am I just not used to javascript functional programming?

By the way, I'm using jQuery (1.4.2) if that helps.

Thank.

+5
source share
4 answers

, jQuery .

$.when() , :

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the 
        page1 and page2 ajax requests, respectively */
   var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
   if ( /Whip It/.test(jqXHR.responseText) ) {
      alert("First page has 'Whip It' somewhere.");
   }
});

!

+5

jQuery 1.5, , $.when()

$.when(getDataFromServerWithAJAXCall("Call 1"), getMoreDataFromServerWithAJAXCall("Call 2")).done(function(a1, a2) {
    var jqXHR = a1[2];
    jqXHR.responseText;
    getDataFromServerWithAJAXCallThatDependsOnPreviousData(jqXHR.responseText);
});

, , .

jsfiddle

0

AJAX / . , , , . , Ajax. , n Ajax, .

0

" "

  • .
  • countdownlatch , , ( .
  • , countdownlatch==0, processAllDataAndShowResult

javascript , countdownlatch , javascript , : countdownlatch - , ( ).

, B A, :

var A,B,C;
var cdlatch = 2;
getDataFromServerWithAJAXCall(whatever, function(AJAXResult) {
    A= AJAXResult;
    getDataFromServerWithAJAXCallThatDependsOnPreviousData(A, function(AJAXResult2) {
        B= AJAXResult2;
        if(--cdlatch === 0){
          processAllDataAndShowResult(A,B,C);
        }
    });
});
getMoreDataFromServerWithAJAXCall(whatever2, function(AJAXResult) {
    C= AJAXResult;
    if(--cdlatch === 0){
      processAllDataAndShowResult(A,B,C);
    }  
});

function processAllDataAndShowResult(A,B,C) {
   //Do stuff
}

, , , , .

0
source

All Articles