只有当异步获取请求完成时,才能继续循环
Only continue for loop when async get request finishes
我正在编写一个工具,该工具将循环遍历id的列表(由id_list
中的id表示)。我们检查一个缓存对象,看看我们是否已经有了id的值。如果我们还没有给定id的值,我们需要发出get
请求来获取相关值,然后将其添加到缓存中。
在执行一个async
获取请求所花费的时间内,整个循环都将运行。这意味着缓存从未实际使用过。在继续循环之前,我是否可以要求get
请求完成?通常,我会通过前面的onSuccess
函数来链接请求,但由于有更改,因此不会发出请求。
cache = {};
var rating;
for (id in id_list){
if (id in cache){
rating = cache[id];
}else{
rating = $.get(~~~async get request happens here~~~);
cache[id] = rating;
}
$(".result").append(rating);//display result in ui
}
如果希望for
循环在每次迭代之间等待,则不能使用它。一种常见的设计模式是为给定的迭代创建一个本地函数,然后在每次异步操作完成时调用它。
假设id_list
是一个具有属性的对象,您可以这样做:
var cache = {};
var ids = Object.keys(id_list);
var cntr = 0;
function next() {
var id;
if (cntr < ids.length) {
id = ids[cntr++];
// see if we can just get the value from the cache
if (id in cache) {
$(".result").append(cache[id]);
// schedule next iteration of the loop
setTimeout(next, 1);
} else {
// otherwise get rating via Ajax call
$.get(...).then(function(rating) {
$(".result").append(rating);
// put rating in the cache
cache[id] = rating;
next();
});
}
}
}
next();
或者,如果id_list
是一个id数组,您可以将其更改为:
var cache = {};
var cntr = 0;
var id_list = [...];
function next() {
var id;
if (cntr < id_list.length) {
id = id_list[cntr++];
// see if we can just get the value from the cache
if (id in cache) {
$(".result").append(cache[id]);
// schedule next iteration of the loop
setTimeout(next, 1);
} else {
// otherwise get rating via Ajax call
$.get(...).then(function(rating) {
$(".result").append(rating);
// put rating in the cache
cache[id] = rating;
next();
});
}
}
}
next();
相关文章:
- 如何让foreach循环等待$http.get完成后再继续
- 试图使循环退出,但它目前只是继续循环100次
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?
- 如果我不这样做会发生什么;t有页码吗?继续循环帖子..为什么需要分页,对于页脚
- 在执行时间循环中使用继续
- 在继续循环之前完成设置超时
- 防止在 jquery ajax 直到加载时继续循环
- 柔性滑动器2在一个方向上继续循环而不工作
- 我怎样才能让旋转木马继续循环
- 中断条件以继续循环
- 在继续循环之前,获取要完成的回调
- 如何使滑块在元素结束时继续循环(如何包裹滑块)
- 如何使我的滑块继续循环
- 只有当异步获取请求完成时,才能继续循环
- 在函数调用中中断或继续循环
- jQuery在ajax成功后继续循环执行
- 等待AJAX完成后再继续循环
- jquery.each在继续循环之前等待函数完成
- jQuery 在 ajax 结束时继续循环
- 为什么这段代码继续循环?