简体   繁体   中英

Protractor can't get value from executescript it returns a promise

In protractor, I have this.

function getText(): string {
    return browser.executeScript(`return 'some text';`);
}

The first one returns a promise and I don't know how to get the value from a promise.

I then tried to do

function getText(): string {
    browser.executeScript(`return 'some text';`).then(function(result) {
        return result;
    });

The problem with the second one is that I can't find a way to make it asynchronous. It only returns when all my code is finished executing.

The thing I'm trying to achieve is :

let text = getText();

Hope someone can help as I couldn't find a working answer to this question.

Edit: I couldn't find a way to place it in a variable outside the function. My current solution is:

browser.executeScript(`return 'some text';`).then(function(result) {
    console.log(result);
    //do your stuff here with the variable.
});
//can't find out how to use it outside the then function as other code runs first. But for now, that way works.

You can use async ... await mechanism for working with promises:

async function getText(): Promise<string> {
  const text = browser.executeScript(`return 'some text';`);
  return text;
});

...
...

let text = await getText();

And if you don't want to wait while your getText method has been finished (I don't know why you need this strange thing) you can just not resolve the Promise:

let text = getText();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM