无法从函数内部访问数组变量 [英] Unable to access array variable from inside a function

查看:54
本文介绍了无法从函数内部访问数组变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 TypeScript 和量角器非常陌生,我想将从下拉列表中提取的所有值放入数组中,以便我可以从另一个页面对其进行验证.

I am very new to TypeScript and protractor and would like to put all the extracted values from a drop list inside an array so that I can validate it from another page.

export class AdditionalCostPage extends BasePage {
  getAllUsageCategoryElements() {
    var usageCategory: string[] = [];

    element
      .all(
        by.xpath(
          "//p-dropdown[@name='usageCategory']/div/div[3]/div/ul/li[*]/span"
        )
      )
      .each(function(element, index) {
        element.getText().then(function(text) {
          console.log('list text from drop list  is ' + text);
          usageCategory.push(text);
        });
      });

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

在结果中,usageCategory 的大小为 0,而且我注意到大小 0 打印在console.log("下拉列表中的列表文本为+ text);"之前.被执行.请建议任何人.提前致谢.

In the result the size of the usageCategory is 0 and also I noticed that the size 0 is printed before "console.log("list text from drop list is " + text);" gets executed. Please suggest anyone. Thanks in Advance.

推荐答案

问题是上面的实现没有正确处理异步.

The problem is implementation above did not handle the async properly.

Size of the array is 0
list text from drop list  is a
list text from drop list  is b
list text from drop list  is c
list text from drop list  is d

考虑使用 await async,它会使一堆这些问题变得更加清晰.

Consider using await async, it would make a bunch of these issues much cleaner.

async getAllUsageCategoryElements() {
    let usageCategory: string[] = [];

    const elms = await element
      .all(
        by.xpath(
          '//p-dropdown[@name='usageCategory']/div/div[3]/div/ul/li[*]/span'
        )
      );

    for (var i = 0; i < elms.length; i++) {
      usageCategory.push(await elms[i].getText());
    }

    return usageCategory;
}

从哪里调用这个函数

const abc = await getAllUsageCategoryElements();
console.log('Size of the array is ' + abc.length);

这篇关于无法从函数内部访问数组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆