Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  54] [ 5]  / answers: 1 / hits: 5755  / 3 Years ago, fri, september 10, 2021, 12:00:00

I'm trying to set a variable within a .then() command which is declared outside of it, and after the whole block finished (the .then()) I'm returning that value.


The problem is, when I return the value, the variable is undefined, but within the .then() block, the variable is loaded.


Here is the example code:


public getValueFromElement(): string {
cy.log("Obtaining the Value");

let myNumber: string; // Here I'm declaring my variable

cy.get(this.labelWithText).then(($element) => {

let originalLabelText: string = $element.text();
let splittedText: string[];
splittedText = originalLabelText.split(": ");

myNumber = splittedText[1]; // Here I'm assigning the value
cy.log("Inside the THEN" + myNumber); //This logs the number correctly

});

return myNumber; // But after I return it using the function, the value is `undefined`!
}

I'm assuming this could be related to the async / sync problem, as the return statement is being executed immediately when the function is called, and the promise created by the .then() is still running, but I don't know how to fix this.


Do you know how I can wait for the .then() to finish first before returning the value?


Thanks!!


More From » typescript

 Answers
2

You say "The problem is, when I return the value, the variable is undefined".


That's because the return myNumber line runs before the cy.get(this.labelWithText).then(($element) => { completes, because the command is running asynchronously.


You need to return the command itself, and also the derived myNumber is returned from inside the .then().


public getValueFromElement(): Chainable<string> {  // cannot return the raw string 
cy.log("Obtaining the Value");

return cy.get(this.labelWithText).then(($element) => {
...
const myNumber = splittedText[1];
cy.log("Inside the THEN " + myNumber)

return myNumber
})
}

Use it like this


getValueFromElement().then(myNumber => {
cy.log("Outside the function " + myNumber)
})

[#888] Monday, September 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;