在再次执行之前等待部分异步功能完成

问题描述 投票:0回答:1

我有一个函数,一旦调用,就调用另一个(同步)创建一个选项卡,然后在执行另一个函数(应该将内容加载到新选项卡)之前等待(异步)两个条件为真。

我试图使函数异步并找到“暂停”其执行的方法,直到条件为真。

var onChosenFileToOpen = function(theFileEntry) { 

$('.nav-tabs li:nth-child(' + $(".nav-tabs").children().length + ') a').click(); //synchronous function that creates a tab
var checker=setInterval(()=>{
  if(currentiframe.contentWindow && currentiframe.contentWindow.editor){//waits those 2 conditions to be true
    currentiframe.contentWindow.readFileIntoEditor(theFileEntry)//content is loaded to that tab
    clearInterval(checker)
  }

},1)};

当有人手动(通过单击按钮/菜单)执行该功能时,此工作正常。但如果一次调用多次,则会创建许多选项卡,只有最后一个选项卡会加载内容。我需要一种方法来等待所述函数的第一次调用以完全结束然后运行下一个。

javascript jquery
1个回答
0
投票

我使用以下方法解决了这个问题(经过几个小时的尝试和错误以及谷歌搜索):

调用main函数后,它会将接收到的值推送到数组并调用另一个函数,该函数创建一个选项卡,将内容(存储在数组的第一个positin中)加载到它,移动数组,然后再次执行以防万一还有更多的价值观。

码:

var callagain=true;
var tabstocreate=[]
var onChosenFileToOpen = function(theFileEntry) { 
tabstocreate.push(theFileEntry)
    thequeue();


};

function thequeue(){

  if(callagain===true && tabstocreate.length>0){

    $('.nav-tabs li:nth-child(' + $(".nav-tabs").children().length + ') a').click(); 

    var checker=setInterval(()=>{
      if(currentiframe.contentWindow.editor){
        currentiframe.contentWindow.readFileIntoEditor(tabstocreate[0])
        tabstocreate.shift()
        clearInterval(checker)
        callagain=true
        if(tabstocreate.length>0){
          thequeue()
        }

      }

    },1)
    callagain=false
  }


}
© www.soinside.com 2019 - 2024. All rights reserved.