2017-02-14 34 views
0

這更像是一個JavaScript問題,但它正在嘗試使用量角器測試來實現。量角器函數返回undefined?

//fileA.js 
element(by.id('page-element').getText().then(function() { 
    var currentPremium = fileB.getSixMonthPremium(); // calls the function in fileB.js 

    element(by.id('page-element').getText().then(function() { 
     console.log(currentPremium); // prints undefined 
     fileB.compareValue(currentPremium, ..., ...,); 
    }); 
}); 


//fileB.js 
this.getSixMonthPremium() = function() { 
    element(by.id('full-premium').isDisplayed().then(function(displayed) { 
     if (displayed) { 
      element(by.id('full-premium').getText().then(function(currentPremium) { 
       console.log('Current Premium - ' + currentPremium); // prints string of $XXX.xx 
       return currentPremium; //seems to be returning undefined? 
      }); 
     } 
    }); 
}); 

當試圖使用變量currentPremium它從函數調用返回後,它總是不確定的。我究竟做錯了什麼?

回答

1

歡迎使用帶有Javascript的異步調用!

您將要從getSixMonthPremium()呼叫中返回承諾,然後在該呼叫恢復後繼續工作。

this.getSixMonthPremium() = function() { 
    return new Promise(function(resolve,reject){ 
     element(by.id('full-premium').isDisplayed().then(function(displayed) { 
      if (displayed) { 
       element(by.id('full-premium').getText().then(function(currentPremium) { 
        console.log('Current Premium - ' + currentPremium); // prints string of $XXX.xx 
        resolve(currentPremium); //seems to be returning undefined? 
       }); 
      } 
     }); 
    }) 
}); 

,那麼你將做類似下面搞定承諾:

fileB.getSixMonthPremium().then(function(premium){ 
    ...handle premium 
}); 
+0

謝謝!我知道這是異步/承諾相關的東西,但我無法通過搜索Google找到我需要的東西。我需要讓自己成爲一本JavaScript書籍或找到一些好的在線內容:) – DrZoo