Marc Kelly
Marc Kelly

Reputation: 3

How to capture promise return and use it in a variable

I'm using the following code to capture a value from an element and use that element in a sendKeys command later on in the code.

getPort = function(){
    $('#Window').element(by.id('Port')).getAttribute('value').then(function(text){
            console.log(text);
            return text;
        });
        };
var port = getPort();

I later on (in the same "it" block) try and call a sendKeys

$('#Window').element(by.id('LinkedIPAddress')).sendKeys('website:' +port);

However the sendKeys command always says the variable port is an undefined value, the console log from the function displays the correct information so I know it is capturing the correct info.

Upvotes: 0

Views: 632

Answers (2)

Brine
Brine

Reputation: 3731

port is undefined because you're only returning to the callback; not your method. You need one more return. This should work:

getPort = function(){
  return $('#Window').element(by.id('Port')).getAttribute('value').then(function(text){
    console.log(text);
    return text;
  });
};

var port = getPort();

@alecxe's answer is also good. Just depends on how you want to work it.

Upvotes: 1

alecxe
alecxe

Reputation: 473873

Let getPort() return a promise:

getPort = function() {
    return $('#Window').element(by.id('Port')).getAttribute('value');
};

And resolve it when you need a real value:

getPort().then(function (port) {
    $('#Window').element(by.id('LinkedIPAddress')).sendKeys('website:' + port);
});

Upvotes: 2

Related Questions