Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How to make for loop wait until Async call was successful before to continue

Hi i am creating a batch update for my local store using for loop and async ajax call.

My problem is that my loop continues even though my ajax call still not yet successfully finished.

How can we manage to make for loop wait unit the response of the ajax response before continuing the loop?

Any help is appreciated. Thanks!!!

Below is my sample code:

var counter =0;
var totalRow = 3000;
for (var i = 0, l = totalRow; counter <= l; i++) {

    var defectssurl = 'https://test.com/mywcf.svc/GetListAllPaging?id=' + counter;

        url: defectssurl,
        method: "POST",
        params: '',
        success: function (resp) {

            console.log("load first 500 records");
            var data = Ext.JSON.decode(resp.responseText); //encode Json List

            if (counter == 0) {
                // Also remove all existing records from store before adding

            Ext.Array.each(data, function (record) {
                counter = counter + 1;

            defectsLocalStore.sync(); // The magic! This command persists the records in the store to the browsers localStorage

            //records is now same as the total records
            if (counter >= totalRow) {

            //continue loop
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        failure: function (resp) {


like image 944
BizApps Avatar asked Dec 25 '22 10:12


1 Answers

Please don't use "for loop". Instead in the success callback increase the counter and re-trigger itself. something like below.

function mySyncFunction (counter, totRecords){
   if(counter === undefined) 
     counter = 0;   
   if(counter >=totRecords) return;

   var defectssurl = 'https://test.com/mywcf.svc/GetListAllPaging?id=' + counter;
        // snip // your code here
     success: function (resp) {
        // snip // your code here
        mySyncFunction(counter, totRecords);
     // snip // your code here
like image 90
Abhi Avatar answered Feb 14 '23 20:02