我有一个递归循环,在函数内部我至少有2个ajax get/post,并且递归发生在第一个ajax get之后。我的函数结构是这样的,
function Loop() {
$.get(url, data, function(result) {
for loop to render the result {
// render the result here
}
for loop to get another data using the result {
$.post(url, result.data, function(postResult) {
// I don't know what it did here since
// I don't have an access to this post
});
// is there a way here that i will not proceed if the post is not done yet?
}
setTimeout("", 1000); // I wait for 1 second for the post to finish
Loop(); // call the recursion
}, "json");
}
谁能告诉我这段代码有什么问题吗?为什么我会收到计算机发出的警告,提示我的脚本导致计算机运行缓慢。我知道此代码是导致此问题的原因,但我不知道解决方法。
我知道 get 内的第二个循环会占用大量内存。有没有办法在ajax post未完成的情况下不循环返回?
最佳答案
您的setTimeout
不会整齐地将代码暂停一秒钟:它只会设置一个计时器(在您的情况下为空)事件在一定时间后关闭。脚本的其余部分将继续与此并行执行。
因此,您当前调用递归函数的频率比您想象的要高得多。这是你的第一个问题。
但是,您最大的问题是,无论您在帖子的结果中做什么,这都完全属于另一个范围,并且您无法从那里突破 Loop
函数。您的代码中没有任何内容可以破坏递归,因此它是无限的,并且速度非常快,并且在此基础上发送 Ajax 请求。
您需要更详细地描述您想要实现的目标,也许有人可以告诉您应该如何实现。唯一确定的是你需要使用回调。我写了一个例子,但它做了很多假设。这与我认为您可能想要实现的目标有很多近似,但毫无疑问,您需要对此进行一些调整以满足您的需求。希望它能让您了解需要使用的工作流程:
function Loop() {
$.get(url, data, function(result) {
for loop to render the result {
// render the result here
}
// this is what you're looping over in your second loop
var postQueue = result.someArray;
renderChildData(postQueue, 0);
}, "json");
}
function renderChildData(array, index) {
// this is just one item in the loop
var currentItem = array[index];
$.post(url, currentItem, function(postResult) {
// we have received the result for one item
// render it, and proceed to fetch the next item in the list
index++;
if(index < array.length) {
renderChildData(array, index);
}
});
}
关于javascript - 递归AJAX帖子,导致计算机运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3252968/