我有一个 jQuery 脚本,它调用 Web API 来获取 JSON 格式的输出。该 API 专为少量连续调用而设计。我需要从 API 获取大量数据,但我不想一点点手动发送输入,因为这需要很长时间。
我不在乎脚本运行需要多长时间,只要不需要有人手动执行某些操作即可。所以我添加了一些延迟。问题是结果现在不符合我将其发送到 API 的顺序,因此我无法将输出与输入连接起来。
如何保持 textareaElem 中的行顺序与输入对齐?
var time = 0;
for (var i = 0; i < value_array.length; i++) {
if (i > 0 && i % 5 == 0) {
time = Math.floor((Math.random() * 45) + 15) * 1000; // Random waiting
} else {
time = 0;
}
(function (textareaElem, value_array, i) {
window.setTimeout(function() {
$.getJSON("myscript.php?var="+encodeURIComponent(value_array[i]), function(result) {
textareaElem.val(textareaElem.val() + (result['val'] + '\n');
});
}, time);
})(textareaElem, value_array, i);
}
编辑:我的代码中有错误。我需要脚本来暂停 API 调用一段时间。上面的代码仅在处理其他行时延迟某些行的处理。这是因为 setTimeout() 是异步的。
这也引入了顺序问题。排序可以通过 @Rodrigo Juarez 答案来解决,但这对解决整个问题没有帮助,因为我需要每隔几次调用就暂停 API 调用。
如何暂停?
最佳答案
这是我找到的解决方案,只需创建和数组,你已经有了每个请求的索引,所以你只需要将数组中的值分配给每个结果,然后使用方法 join
var time = 0;
var text = [];
var index = 0;
//function to be called to retrieve the data
var getData = function (index) {
$.getJSON("myscript.php?var="+encodeURIComponent(value_array[index]), function(result) {
text[index] = result.val + '\n';
textareaElem.val(text.join(""));
if (index < value_array.length){
getData(index++);
}
});
};
//Just calling the function with index 0
if (value_array.length) {
getData(0);
}
关于javascript - 在 AJAX API 调用之间等待时保持输出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829298/