我知道这个问题已经被问过无数次了,但我一生都无法弄清楚如何让这个答案在我的情况下起作用:等待异步 javascript 函数返回
我在外循环中循环播放一些“电视频道”,然后在内循环中循环播放一周中的日期。在内部循环中,我向服务器发出 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 解决方案
非常感谢!