【问题标题】:Wait partially async function to finish before executing it again在再次执行之前等待部分异步函数完成
【发布时间】:2019-04-29 02:30:07
【问题描述】:

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

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

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)};

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

【问题讨论】:

  • 如果您可以使用 Stackoverflow JS Fiddle 功能发布一个工作示例,那么调试起来会容易得多。
  • event 准备好时,它会怎样?感觉这样会少很多 hacky
  • 你可以查看事件,也许是事件>并添加功能
  • 你需要坚持使用 jQuery 来完成这个任务吗?听起来像是异步/等待的用例。另外我会考虑使用 while() 循环
  • 你需要的是一个队列(比如thisthat,甚至using jQuery

标签: javascript jquery


【解决方案1】:

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

一旦调用 main 函数,它将接收到的值推送到一个数组并调用另一个函数,该函数创建一个选项卡,将内容(存储在数组的第一个位置)加载到它,移动数组,然后再次执行自身如果里面还有更多的值。

代码:

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
  }


}

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多