返回语句比量角器中的代码片段更早执行

时间:2018-05-25 13:11:51

标签: typescript 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()`
}

因此,即使该方法为真,该方法也会返回false。

1 个答案:

答案 0 :(得分:0)

实际上returnthis.ClinicList.getText()后面执行。为了清楚地理解,你需要知道所有的protractor API都是执行Async并返回promise,你还需要了解promise。

当Nodej执行此功能时,当运行到行this.ClinicList.getText().then()时,此行返回一个pomise,然后移动以运行下一行:return Outcome

关键点是getText()是Async,因此从页面读取文本的实际工作是执行的,因此实际工作的开始时间晚于执行return Outcome的nodejs。

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