[英]for-loop in for-loop doesn't execute in order with async/await function
我在一个循环(带索引 i)中有一个循环(带索引 j),其中有一个 await function,调试后,我发现有时一对(i,j)执行不止一次。 我完全糊涂了-_-
有人可以解释一下吗? 非常感谢!
这是代码:
我将 searchFunc 添加到输入元素。
async function searchFunc() {
let results = [];
let notebooksP = await queryData(url1);
notebooks = notebooksP.value;
// debugger;
for (let i = 0; i < notebooks.length; i++) {
let noteIds;
let noteIdsP = await queryData(urlBase + notebooks[i].id);
noteIds = noteIdsP.value;
debugger;
for (let j = 0; j < noteIds.length; j++) {
console.log("runing at i=", i, ", j=", j, );
let noteContentsP = await queryData(urlBase + noteIds[j].id);
let data = noteContentsP.value;
// debugger;
let content = data.content;
let idx = content.search(key);
if (idx != -1) {
let res = {};
res.notebookId = notebooks[i].id;
res.noteId = noteIds[j].id;
results.push(res);
console.log("found at i=", i, " j=", j);
}
}
}
function queryData(path) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', path);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
var ret = xhr.responseText;
resolve({value: JSON.parse(ret)});
} else {
reject('error');
}
}
})
}
const searchContent = debounce(searchFunc, 500);
searchBox.addEventListener('input', searchContent);
function debounce(fn, wait) {
let timeout = null;
return function () {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait);
}
}
如果您在每次按键时都触发搜索,则存在设计缺陷。 这可能会导致响应排序等问题。 但是,忽略此问题,解决您遇到的问题的一种简单方法是阻止 function 同时被调用两次,使用变量来跟踪它何时运行:
let searching = false;
async function searchFunc() {
if (searching) {
return;
}
searching = true;
let results = [];
let notebooksP = await queryData(url1);
notebooks = notebooksP.value;
// debugger;
for (let i = 0; i < notebooks.length; i++) {
let noteIds;
let noteIdsP = await queryData(urlBase + notebooks[i].id);
noteIds = noteIdsP.value;
for (let j = 0; j < noteIds.length; j++) {
console.log("runing at i=", i, ", j=", j, );
let noteContentsP = await queryData(urlBase + noteIds[j].id);
let data = noteContentsP.value;
// debugger;
let content = data.content;
let idx = content.search(key);
if (idx != -1) {
let res = {};
res.notebookId = notebooks[i].id;
res.noteId = noteIds[j].id;
results.push(res);
console.log("found at i=", i, " j=", j);
}
}
}
searching = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.