我试图在 .then() 命令中设置一个在其外部声明的变量,并且在整个块完成后(.then())我将返回该值。
问题是,当我返回值时,变量未定义,但在 .then() 块内,变量已加载。
这是示例代码:
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`!
}
Run Code Online (Sandbox Code Playgroud)
我假设这可能与异步/同步问题有关,因为该return语句在调用函数时立即执行,并且由创建的承诺.then()仍在运行,但我不知道如何解决这个问题。
.then() …