JavaScript(量角器)中函数的值返回为未定义 [英] value of a function in JavaScript(protractor) returns as undefined
问题描述
我正在使用量角器来检索文本.
im using protractor to retrieve a text.
其中一个功能是
//get the Impersonation ID
this.getUserSessionID = function(){
//get whole text
UserImpersonateTextElement.getText().then(function(text) {
var tempText = text;
var startString = 'session ID is ';
var sessionID = tempText.substring(tempText.lastIndexOf(startString)+startString.length,tempText.length);
console.log('sessionID is:'+sessionID);
return sessionID;
});
};
并且我在另一个js(我在其中导入了上述js)文件中调用了该函数
and im calling the function in another js(where i imported the above js) file
var getUserImpersonationID = ImpersonationSuccessPage.getUserSessionID();
当我尝试
console.log('User Impersonation ID is:'+getUserImpersonationID);
我得到 undefined 作为值.
i get undefined as the value.
但是函数中的console.log('sessionID is:'+sessionID);
显示正确的值.
but the console.log('sessionID is:'+sessionID);
in the function displays proper value.
谁能建议我在这里做错了什么?
Can anyone suggest what im doing wrong here?
推荐答案
获取文本的内部调用返回一个承诺.继续并返回该承诺,然后您可以在对 getUserSessionID 的调用中链接一个 then
.示例
The internal call to get text returns a promise. Go ahead and return that promise and then you can chain a then
in the call to getUserSessionID. Example
this.getUserSessionID = function(){
//get whole text
return UserImpersonateTextElement.getText().then(function(text) {
var tempText = text;
var startString = 'session ID is ';
var sessionID = tempText.substring(tempText.lastIndexOf(startString)+startString.length,tempText.length);
console.log('sessionID is:'+sessionID);
return sessionID;
});
};
在通话中你会这样做:
getUserSessionID().then(function(sessionId){
console.log('You session ID is ',sessionId);
})
或者,由于expect 假设要解决该承诺,您可以检查您是否有一个带有expect 的ID:
Or, since expect is suppose to resolve that promise you can check if you have an ID with expect:
expect(this.getUserSessionID()).not.toBeNull();
这篇关于JavaScript(量角器)中函数的值返回为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!