gpt4 book ai didi

javascript - 如何让for循环等到异步调用成功后再继续

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:24:38 25 4
gpt4 key购买 nike

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

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

我们如何设法让 for 循环等待单元在继续循环之前等待 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) {

}
});

}

最佳答案

请不要使用“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
});

关于javascript - 如何让for循环等到异步调用成功后再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22978843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com