内联函数中无法访问Typescript方法变量

时间:2019-01-23 18:54:00

标签: javascript typescript variables scope protractor

我有下面的代码,我在一个内联函数中将值加载到数组usageCategory中。但是,当我尝试在此函数之外打印值时,不会打印任何内容。

ItemsPresenter

我在这里做错了什么?我如何在内联函数之外访问这些数组值?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

使用ElementArrayFinder.prototype.map

这可能是使用.map函数的好时机,因为它将把ElementArrayFinder对象转换为您创建的对象列表。 http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map在量角器示例中(在链接中),地图返回对象列表。对于您的情况,您需要等待该元素的文本,然后在地图回调函数中将其返回。

async getAllUsageCategoryElements() {
    // extract all the droplist elements and put into an array so that I can validate them from another page.
    const spans = this.addAdditionalCostDialogue.usageCategoryDropListContainer
        .all(by.tagName('li')).all(by.tagName("span"));
    // Map over an ElementArrayFinder to get a list of returned items from
    // map operation. In this case, we are returning a list of strings
    const usageCategories = await spans.map(async (el) => {
      const text = await el.getText();
      // console.log(`printing directly ${text}`);
      return text;
    });

    console.log("Size of the array is " + usageCategories.length);
    for (let usageCategory of usageCategories) {
      console.log(`printing text ${usageCategory}`);
    }
}

答案 1 :(得分:0)

您的代码中有两个问题:

1)usageCategory是局部变量,不是函数getAllUsageCategoryElements的属性,因此不能使用that.usageCategory.push(text);,而只能使用usageCategory.push(text);

2)getText()是异步API,以下同步代码将在getText()之前执行,
,因此 usageCategory.length 0 。您需要将这些同步代码放在then()之后的下一个getText()中,以使其在getText()之后执行。

console.log("Size of the array is " + usageCategories.length);
for (let usageCategory of usageCategories) {
  console.log(`printing text ${usageCategory}`);
}

更正的代码:

getAllUsageCategoryElements(){

    var usageCategory: string[] =  [];


    // extract all the droplist elements and put into an array so that I can validate them from another page.
    this.addAdditionalCostDialogue
        .usageCategoryDropListContainer
        .all(by.tagName('li'))
        .all(by.tagName("span"))
        .each(function (element, index) {

            element.getText().then(function (text){
                //console.log("printing directly " + text);
                // the above code works fine and prints all the drop list contains but when I try to add it to an array
                usageCategory.push(text);
            })
    })

    .then(function(){

        console.log("Size of the array is " + usageCategory.length);

        usageCategory.forEach(element => {
            console.log("Printing text " + element);
        }); 

        return usageCategory;
    });

}