【问题标题】:Parallel execution of the functions and waiting for their completion并行执行函数并等待它们完成
【发布时间】:2013-11-21 21:51:31
【问题描述】:

我怎样才能等到两个函数结束,并且只有在调用回调之后才能继续脚本。

我关注了 jQuery deferred.then(),但我不明白在我的情况下如何使用它

GoogleDriveModule.checkAuth(function(authResult) {
  if (authResult) {
    return parts_count += 1;
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  if (authResult) {
     return parts_count += 1;
  }
});

【问题讨论】:

    标签: javascript jquery asynchronous callback deferred


    【解决方案1】:

    创建两个延迟对象并在回调中解析它们。然后您可以使用$.when 等待两个延迟:

    var googleDone = $.Deferred(),
        dropboxDone = $.Deferred();
    
    GoogleDriveModule.checkAuth(function(authResult) {
      googleDone.resolve();
      if (authResult) {
        return parts_count += 1;
      }
    });
    
    DropboxModule.isAuthenticated(function(authResult) {
      dropboxDone.resolve();
      if (authResult) {
         return parts_count += 1;
      }
    });
    
    $.when(googleDone, dropboxDone).then(function() {
        alert("Both authentication checks completed.");
    });
    

    【讨论】:

    • @Karl-AndréGagnon:我不认为差异是可衡量的,但绝对而言它肯定会“更慢”。这里的主要吸引力在于您可以继续将任何延迟(主或任何一个孩子)链接或集成到任何其他异步管道中。
    【解决方案2】:

    如果它们准备好了,你可以有 2 个布尔值并检查回调函数:

    var gDriveREADY = false, dBoxREADY = false;
    GoogleDriveModule.checkAuth(function(authResult) {
        if (authResult) {
            return parts_count += 1;
        }
        gDriveREADY = true;
        doSomething()
    });
    
    DropboxModule.isAuthenticated(function(authResult) {
        if (authResult) {
            return parts_count += 1;
        }
        dBoxREADY = true;
        doSomething();
    });
    
    function doSomething(){
        if(dBoxREADY && gDriveREADY){
            //Your code
        }
    }
    

    【讨论】:

      【解决方案3】:

      在回调中,您可以切换其他函数检查的简单标志:

      var driveDone = 0
        , dropDone = 0
        ;
      GoogleDriveModule.checkAuth(function(authResult) {
        driveDone = 1;
        if (authResult) {
          parts_count += 1;
        }
        if(dropDone){
         bothDone();
        }
      });
      
      DropboxModule.isAuthenticated(function(authResult) {
        dropDone = 1;
        if (authResult) {
           parts_count += 1;
        }
        if(driveDone){
         bothDone();
        }
      });
      function bothDone(){}
      

      这比 deferred 方法的开销更少,但不是很干净。

      【讨论】:

        猜你喜欢
        • 2019-11-07
        • 1970-01-01
        • 2016-02-21
        • 2012-03-04
        • 2014-08-23
        • 2015-09-16
        • 2021-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多