无法从函数内部访问数组变量
我对 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);