我的问题是,有时这些选项会加入混乱。我的代码如下:
问题:这是由于async
电话。你当前的代码只是发送请求到一个文件,然后跳转到下一个迭代,它会发送请求并跳转到下一个等等。你真的无法控制响应什么时候回复,也没有控制权来控制它。
解决方案:既然你正在处理async
过程的更好,如果你使用递归函数在for循环。看下面的代码来理解我的意思。
function GetFile(fileNumber) {
$.get("./file" + fileNumber + ".txt", function(data) {
$("select").append("<option>" + data + "</option>");
fileNumber++; // since the files was read successfully lets increment the number to next file
if(fileNumber <= n){ // if we have not reached the limit
GetFile(fileNumber); // get the next file
}
});
}
GetFile(1); //initiate the recursive function by passing the first number
由于您没有提供什么n
是我刚才用它作为是在我的代码也一样,考虑的变量可在该范围的详细信息。
解释了解决方案:创建一个函数,接受一个数字作为输入并执行该文件一个get
请求名为"file" + fileNumber + ".txt"
内success
回调get
功能,我会增加数量,并检查其小于或等于极限n
如果它小于或等于那么我继续并通过传递新的号码来调用相同的功能。这将持续到我们达到极限。
注意:如果任何请求发生错误,上述逻辑将停止。如果您想要继续,即使响应中有错误,您也可以添加.fail()
处理程序..请参见下文。
$.get("./file" + fileNumber + ".txt", function(data) {
//above shown logic
}).fail(function() {
console.log("There was an error while fetching file"+fileNumber +".txt");
fileNumber++;
if(fileNumber <= n){ // see if next file exist
console.log("Processing next file!!");
GetFile(fileNumber); // get the next file
}
});
因为异步调用会在不同的时间回来。与您的设计有关的问题是,进行所有这些呼叫是非常低效的。 – epascarello