gpt4 book ai didi

javascript - 仅当异步 get 请求完成时才继续 for 循环

转载 作者:行者123 更新时间:2023-11-28 18:55:44 25 4
gpt4 key购买 nike

我正在编写一个工具,它将循环遍历 id 列表(由 id_list 中的 id 表示)。我们检查缓存对象以查看是否已经有 id 值。如果我们还没有给定 id 的值,则需要发出 get 请求来获取关联的值,然后将其添加到缓存中。

在执行一个async get 请求所需的时间内,整个循环都会运行。这意味着缓存从未被实际使用过。无论如何,我是否可以要求 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 是一个 ids 数组,您可以将其更改为:

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

关于javascript - 仅当异步 get 请求完成时才继续 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662425/

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