小编Jor*_*rge的帖子

如何在返回值之前等待 Cypress then() 命令完成?

我试图在 .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() …

javascript promise typescript cypress

5
推荐指数
1
解决办法
9187
查看次数

标签 统计

cypress ×1

javascript ×1

promise ×1

typescript ×1