2016-07-14 74 views
0

我正在使用守夜來寫硒測試(與您一樣)。守夜的執行方法

我有一個回調定義,我想最終返回一個值(自定義命令在夜間)。問題是,retValue變量不會改變它的價值,即使我看到裏面的console.log

var _someCallBack = function() { 
    var retValue = false; 
    browser 
     .variousNightwatchTasks() //place holder for other things 
     .execute(function (d) { 
      //Other custom work injected into the page 
      return $("span.header_title").length > 0; //I need this true|false 
     }, [], function(r) { 
      retValue = r.value; //has the changes; the following outputs as expected 
      console.log("r = {0} {1}".format(JSON.stringify(r), retValue)); 
    }); 

    //Other things ... 
    console.log(retValue); //always false which is the problem. 
    return retValue; //This return needs to execute. I must return the value. 
} 

值變化我敢肯定,這是由於一些JavaScript的細微差別,我錯過了那麼我怎麼能解決這個問題發生了什麼事? (前者比後者更重要)

更新:return retValue是一個必要位。此函數用於回調自定義nightwatch命令,該命令使用if語句中的返回值。

回答

1

execute注入的函數是異步執行的,並且在返回_someCallBack時尚未調用。 您可以提供回調函數來接收結果:

var _someCallBack = function(callback) { 
    browser 
     .variousNightwatchTasks() //place holder for other things 
     .execute(function (d) { 
      //Other custom work injected into the page 
      return $("span.header_title").length > 0; //I need this true|false 
     }, [], function(r) { 
      callback(r.value); 
     }); 
} 

_someCallBack(function(result){ 
    console.log(result); 
}); 
+0

恐怕這並沒有解決任何問題。 'function(r){callback(r.value); }'部分總是正常工作。它在那之後讀取數值。即使在您的配置中(嵌套回調)也會產生完全相同的行爲。我需要從'_someCallBack'返回'r.value' –

+0

不可能從'_someCallBack'返回'r.value',並且永遠不會。另一種選擇是返回一個承諾,但調用函數將不得不解決它。你能提供一個使用示例嗎? –