jquery callback methods for asynchronous loop to finish

Some times jquery loop statement will not wait until the ajax call completion.
For this case we can use the jquery callback method for looping ajax calls.

In the below example arrayValue is passed into a call back function. this function will  be executed until we call the 'callback()' (which is called in the else part).
we need to write this function inside a function.

function parentFunction()
{
var deferred = $.Deferred();


(function Task(i,callback)
{
if(i<arrayValue.length)

/*your code here*/
var temp = yourFunctionCall(arrayValue[i]); 
temp.done(function()
{
Task(i+1,callback)
})
}
else
{
//this call will terminate the function
callback();
}
})
(0,function(){alert('Completed');deferred.resolve();});


return deferred.promise(); 
}



Please refer the following links for more details Link1 , Link2

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

Add content type to SharePoint List/Library using REST API

A type named 'SP.Data. could not be resolved by the model error