Javascript for loop in for loop notes';t使用异步/等待功能按顺序执行

Javascript for loop in for loop notes';t使用异步/等待功能按顺序执行,javascript,promise,async-await,Javascript,Promise,Async Await,我有一个循环(带索引j)在一个循环(带索引I)中,其中有一个等待函数,在调试之后,我发现有时某对(I,j)执行不止一次。我完全糊涂了-_- 有人能解释一下吗?非常感谢 代码如下: 我将searchFunc添加到输入元素 异步函数searchFunc(){ 让结果=[]; let notebooksP=wait queryData(url1); 笔记本=笔记本电脑p.value; //调试器; for(设i=0;i

我有一个循环(带索引j)在一个循环(带索引I)中,其中有一个等待函数,在调试之后,我发现有时某对(I,j)执行不止一次。我完全糊涂了-_-

有人能解释一下吗?非常感谢

代码如下:

我将searchFunc添加到输入元素

异步函数searchFunc(){ 让结果=[]; let notebooksP=wait queryData(url1); 笔记本=笔记本电脑p.value; //调试器; for(设i=0;i<1.length;i++){ 让noteIds; 让noteIdsP=wait queryData(urlBase+notebooks[i].id); noteIds=noteIdsP.value; 调试器; for(设j=0;j
函数查询数据(路径){
返回新承诺(功能(解决、拒绝){
var xhr=new XMLHttpRequest();
xhr.open('get',path);
xhr.send(空);
xhr.onreadystatechange=函数(){
如果(xhr.readyState!=4)返回;
如果(xhr.readyState==4&&xhr.status==200){
var ret=xhr.responseText;
解析({value:JSON.parse(ret)});
}否则{
拒绝(“错误”);
}
}
})
}
const searchContent=debounce(searchFunc,500);
searchBox.addEventListener('input',searchContent);
函数去抖动(fn,等待){
让timeout=null;
返回函数(){
如果(超时!==null)clearTimeout(超时);
超时=设置超时(fn,等待);
}
}

如果在每个按键上都触发搜索,则此处存在设计缺陷。这可能导致响应顺序等问题。但是,忽略此问题,解决问题的一个简单方法是使用变量跟踪何时调用函数,以阻止函数同时被调用两次它正在运行:

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;
}
let search=false;
异步函数searchFunc(){
如果(搜索){
回来
}
搜索=真;
让结果=[];
let notebooksP=wait queryData(url1);
笔记本=笔记本电脑p.value;
//调试器;
for(设i=0;i<1.length;i++){
让noteIds;
让noteIdsP=wait queryData(urlBase+notebooks[i].id);
noteIds=noteIdsP.value;
for(设j=0;j
searchFunc从何处运行?添加
console.trace('searchFunc已调用')
searchFunc
函数的开头。我想你会发现你同时有多个调用。
控制台。trace
会将调用堆栈转储到控制台。查看该调用堆栈,看看是谁调用了
searchFunc
来解释这两个调用。(我在你的成绩单中看到两个)是的,它在listener中通过setTImeout函数调用了两次(我在问题中添加了一些代码以澄清问题),您能告诉我如何更正它吗?谢谢!不客气。如果答案对您有帮助,请向上投票/标记为答案。