Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for Cypress then() command to finish before returning a value?

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

like image 849
Jorge Avatar asked Oct 20 '25 19:10

Jorge


1 Answers

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)
})