如何使循环等待,直到异步调用成功才能继续 [英] How to make for loop wait until Async call was successful before to continue

查看:522
本文介绍了如何使循环等待,直到异步调用成功才能继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在使用for循环和异步ajax调用为我的本地商店创建批量更新。

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

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

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

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

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!!!

以下是我的示例代码:

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

        }
    });

}


推荐答案

请不要不要用循环。相反,在成功回调中增加计数器并重新触发自身。类似下面的东西。

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
});

这篇关于如何使循环等待,直到异步调用成功才能继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆