Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - 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;

    Ext.Ajax.request({
        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) {
                defectsLocalStore.getProxy().clear();
                // Also remove all existing records from store before adding
                defectsLocalStore.removeAll();
            }

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

            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) {
                pCallback();
            }

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

        }
    });

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
   Ext.Ajax.request({
     url:defectssurl,
        // snip // your code here
     success: function (resp) {
        // snip // your code here
        counter++;
        mySyncFunction(counter, totRecords);
     }
     // snip // your code here
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...