Tuesday, February 25, 2014

Recursively call Asynchronous function and wait for finish all before proceeding in JavaScript

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 

Tuesday, February 11, 2014

Friday, February 7, 2014

Iterate (Loop) Object (Key value pair) in JavaScript and JQuery

Let assume y is our object which has following data and you need to iterate it in native JavaScript

var y = {1: "2", name: "value", sN: "sV"}
$.each(y,function(k,v){alert(k + v)});

in jQuery you can do the same thing like below



var Y = {1: "2", name: "value", sN: "sV"}
for (var k in Y) {
        if (y.hasOwnProperty(k)) {
           alert(y[k]); // value
           alert(k); // key
        }
    }