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!!