小编典典

如何使循环等待异步调用成功后才能继续

ajax

嗨,我正在使用for循环和异步ajax调用为本地存储创建批处理更新。

我的问题是,即使我的ajax调用仍未成功完成,我的循环仍会继续。

在继续循环之前,我们如何设法使循环等待单元响应ajax响应?

任何帮助表示赞赏。谢谢!!!

下面是我的示例代码:

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) {

        }
    });

}

阅读 386

收藏
2020-07-26

共1个答案

小编典典

请不要使用“ for循环”。而是在成功回调中增加计数器并重新触发自身。像下面这样。

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
});
2020-07-26