【发布时间】:2011-07-01 06:16:58
【问题描述】:
我知道这个问题已经被问过无数次了,但我一生都无法弄清楚如何让这个答案在我的情况下起作用:wait for async javascript function to return
我在外循环中循环播放一些“电视频道”,然后在内循环中循环播放一周中的日期。在内部循环中,我向服务器发出 ajax 请求以获取数据,然后像这样存储/缓存它以供以后使用
var dates = []; //<-- Contains a list of dates for the coming week
var baseUrl = "http://www.someserver.com";
var storedChannels = [1,2,3,4,5,6,7,8,9,10,45,23,56,34,23,67,23,567,234,67,345,465,67,34];
for(ch = 0; ch < storedChannels.length; ch++) {
var channel = storedChannels[ch];
for(d=0; d < 7; d++) {
var currentDate = dates[d];
ajax({
url: baseUrl+"?ch="+channel+"&dt=currentDate"+,
complete: function(res) {
CMLocalStore.setString('ch' + ch + "_" + scheduleDay, res);
},
});
//Want to wait here till the ajax request completes.
//Do not want to continue to next iteration.
//Do not want to fire of 50 bazillion ajax requests all at once
//Why? Very limited bandwidth scenario, plenty of channels
}
}
PS:请不要使用 JQuery!仅限纯 JS 解决方案
非常感谢!
【问题讨论】:
-
在“完成”事件函数中不能移动你的等待代码吗?
-
'ajax({ ... })'来自哪里?顺便说一句,如果您不希望它是异步的,它就不是 ajax。你想要 SJAX ;)。原来的xmlhttp.open("GET",url,true);电话在哪里?如果您将true更改为false,它将变为非异步。 -
gnur,如果您的正确答案应该发布,以便我奖励您。让我看看。
-
@n4rzul 您不想在循环中使用同步请求,因为您的 JavaScript 将接管浏览器,直到循环完成。
-
不要使用同步 AJAX!它将完全冻结浏览器。
标签: javascript wait synchronous