我有一个函数,可以正确检索元素的索引,即文本===“ check”。它清楚地打印在console.log中:
function getIndex() {
return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) {
colorList.forEach(function (elem, index) {
elem.getText().then(function (text) {
if (text == "check") {
console.log(index);
return index;
}
});
});
});
}
然后,我尝试了许多不同的方法,如何从中检索数据,但没有成功。最后一种方法是:
var res = null;
webDriver.promise.fullyResolved(getIndex()).then(function (index) {
res = index;
});
console.log(res);
因此,在这里我尝试在函数内部初始化res值,这可以保证任何promise解析,但是它不起作用,并返回null。
我认为,我在getIndex()函数中犯了一个错误,也许,我将返回操作符放在了错误的位置,但是在这里我需要帮助。我完全不知道如何使它工作。请帮助。
最佳答案
您使问题变得过于复杂,请使用reduce()
而不是“ forEach”:
function getIndex() {
return element.all(by.css(".palette__item > span")).reduce(function (acc, elem, index) {
return elem.getText().then(function (text) {
if (text == "check") {
return index;
}
});
}, -1);
}
用法:
getIndex().then(function (index) {
console.log(index);
});
附带说明-尽量不要在定位器中使用
ng-scope
类-它是纯技术角度特定的类,不会给定位器带来任何意义。关于javascript - 如何从 Protractor 的 promise 链中检索数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41245152/