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

Jor*_*rge 5 javascript promise typescript cypress

我试图在 .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()你知道我如何在返回值之前先等待完成吗?

谢谢!!

Mic*_*nes 5

你说“问题是,当我返回值时,变量是未定义的”。

这是因为该行在完成之前return myNumber运行,因为该命令是异步运行的。cy.get(this.labelWithText).then(($element) => {

您需要返回命令本身,并且myNumber派生命令也是从.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
  })
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它

getValueFromElement().then(myNumber => {
  cy.log("Outside the function " + myNumber)
})
Run Code Online (Sandbox Code Playgroud)