Javascript method chaining

Didn't know how else to put this.

Say I have a JavaScript method that makes some AJAX calls:

function makeAJAXCalls()
{
    // who knows how long this will take
}

And I don't want the next function to execute until all the AJAX calls are complete. I also don't want to put the next function call into the success callback for the AJAX call.

Is there a way I can like chain these, so the next function doesn't get called until makeAJAXCalls() is done everything it needs to do?


var queueCount =0;
function makeAjaxCalls()
{
    queueCount+=7; // or however many calls you need to make.
    // make your ajax calls. onSuccess (or failure), call checkQueue();
}
function checkQueue()
{
    queueCount--;
    if (queueCount <=0)
    {
       doNext();
    }
}

这使得调用异步,这可能是这里的意图。


You could use jQuery's $.when() functionality.

$.when(makeAjaxCalls()).done(function () { 
   // Do other things here 
});

You can even add multiple functions to the when if you wanted all of those to be completed first. These are all called Deferred Objects.


You are really limiting your options. AJAX is asynchronous by nature (unless you use synchronized xhrs, which you don't want because they freeze the browser). So your only option is to handle it in the callback, because the callbacks are the only way you know the request has completed, and where the data from the requests gets passed when they complete.

Because you have multiple callbacks, and you want to wait till they are all done, you can put the same function call in all the callbacks, and that function can track which responses have come back, and only proceed if all responses are there.

so you can do something like

var resultsHolder = [];
var syncer = function(response){
    // add results to resultsHolder on call

    if (resultsHolder.lengh === numberExpected) {
     //proceed
    }
}

then use syncer in your makeAllRequests method

链接地址: http://www.djcxy.com/p/55306.html

上一篇: 在javascript中异步回调的结构:同步异步

下一篇: Javascript方法链接