value of a function in JavaScript(protractor) retu

2019-07-27 06:56发布

问题:

im using protractor to retrieve a text.

one of the function is

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

and im calling the function in another js(where i imported the above js) file

var getUserImpersonationID = ImpersonationSuccessPage.getUserSessionID();

and when i try

console.log('User Impersonation ID is:'+getUserImpersonationID);

i get undefined as the value.

but the console.log('sessionID is:'+sessionID); in the function displays proper value.

Can anyone suggest what im doing wrong here?

回答1:

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

In the call you'd do:

getUserSessionID().then(function(sessionId){
  console.log('You session ID is ',sessionId);
})

Or, since expect is suppose to resolve that promise you can check if you have an ID with expect:

expect(this.getUserSessionID()).not.toBeNull();


回答2:

You don't return from the getUserSessionID function, you only return from the then callback. In fact, you cannot return a value, as your function is asynchronous. You need to return the promise.

this.getUserSessionID = function(){
    return UserImpersonateTextElement.getText().then(function(text) {
//  ^^^^^^
        var startString = 'session ID is ';
        var sessionID = text.substring(text.lastIndexOf(startString)+startString.length, text.length);
        console.log('sessionID is:'+sessionID);
        return sessionID;
    });
};

and then use it like this:

var promise = ImpersonationSuccessPage.getUserSessionID();
promise.then(function(getUserImpersonationID) {
    console.log('User Impersonation ID is:'+getUserImpersonationID);
});