-1

Return statement gets executed earlier than the piece of code in protractor

public newcc(newc:string):boolean
{
  var Outcome:boolean=false;

  this.Cc.getText().then(function (text){
    var Name=text.toString();
    var str_array = Name.split(',');

    console.log("Cce : "+Name);

    for(var i:number=0;i<str_array.length;i++) {
      // if the name is found then make the outcome true and break 
      if(str_array[i]==cc) {
        console.log(str_array[i] +" is equal to "+ClinicName);
        Outcome=true;
        console.log("Inside Outcome " +Outcome);
        break;
      } else {
        console.log(str_array[i] +" is not equal to "+Cc); 
      }
    }        
  });  

  return Outcome;
  // the return always exectued earlier than above `this.ClinicList.getText()`
}

Because of this always the method returns false even if it is true.

DtestA
  • 55
  • 9
  • 1
    It's not clear what your question is. The code is meant to be executed after the return. – Mozahler May 25 '18 at 13:16
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 25 '18 at 13:26

1 Answers1

0

Actually return is executed behind of this.ClinicList.getText(). To get a clear understanding, you need to know all protractor API are executed Async and return promise, you also need to understand promise.

When Nodejs execute this function, when run to line this.ClinicList.getText().then(), this line return a pomise, then move to run the next line: return Outcome.

The key point is the getText() is Async, so the actual work to read text from page is executed asynce, so the actual work is start later than nodejs executing return Outcome.

public CliniclistClinicAvailability(ClinicName:string): any
{

  // i guess this.ClinicList is decleared as `element.all()`

  return this.ClinicList.getText().then(function (texts){
     // texts is an Array<string>
     return texts.includes(ClinicName);
  )};
}

// how to use above function:
// CliniclistClinicAvailability return a promise, 
// you need to consumer the promise's eventually value in `then()`
CliniclistClinicAvailability('Test').then(function(isAvailable:boolean){
   console.log('isAvailable: ' + isAvailable);
});
yong
  • 13,357
  • 1
  • 16
  • 27