In recently i have to work with problem which recursively call asynchronous methods. I tried with differed object $.when.appy ; but with large number of calls this method didn't show any constant result. Therefore i used some call back function with to archive this task.
Here I'm a keeping a TrackCalls object to track async calls and their returns. If any error occurred loop will be stopped and notify.
var TrackCalls = { "callCount" : 0 , "receivedCount":0 , "errorCount":0};
function callBack(){ setTimeout(function () { if (TrackCalls.callCount == TrackCalls.receivedCount) { // all async call received }
else if (TrackCalls.errorCount > 0) {
// Error occurred in one of async call }
else {callback();
}
}, 2000);
}
function AsyncCall( finised , failed){TrackCalls.callCount++;
$.ajax({url: "test.html"}) .done( function(){TrackCalls.receivedCount++;
finised();
})
.fail( function(){ TrackCalls.errorCount++;
failed();
});
}
function main(){ for ( i=0; i<100 ; i++) {AsyncCall(finishedOneCall,failedOneCall);
}
callBack();
}
function finishedOneCall(){ // Your code};
function failedOneCall(){ // Your code};
main(); // start main
Comments