好吧,我有这段代码,我正在尝试,并在写作失败。我想要做的是确保传递给函数的索引位于页面上可用元素的范围内。而且,如果是,则返回一个元素引用。获得量角器的承诺,变量和结果同步
假设我有以下几点:
3210所以,我有这样的功能:
function getRow(index) {
// get count of rows.
var count = $$('li').count();
// Ensure a parameter has been passed.
if (!index) {
throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
}
// Ensure the parameter is within bounds
if (index < 0 || index >= count) {
throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
}
return $$('li').get(index);
}
以上将失败,因为数是不是真的算,而是一个承诺。
所以,我试着用各种方法修改它。我以为会是成功的一个如下:
// get count of rows.
var count;
$$('li').count().then(function(c) { count = c; });
或
// get count of rows.
var count = $$('li').count().then(function(c) { return c; });
我已经变得沮丧,并试图如果抛出整个thenable函数中块,但不会“看“索引。
(每次我想我已经想通了这一点,我不感谢您的任何和所有帮助!)
UPDATE:
继建议下面我试着修改我的代码:
function getRow(index) {
//get count of rows.
var count = $$('li').count().then(function(c) {
return function() {
return c;
}
});
protractor.promise.all(count).then(function(count) {
// Ensure a parameter has been passed.
if (!index) {
throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
}
// Ensure the parameter is within bounds
if (index < 0 || index >= count) {
throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
}
});
return $$('li').get(index);
}
但因为失败了,protractor.promise.all().then()
块内,index
是不确定的。此外,在错误消息中,我甚至没有得到count的值。
> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through
也许是因为你在单个对象上调用'index'而不是数组(你在你的定位器中缺少'.all')? 'var count = element.all(by.css(...))'help?然后使用'.each'或'.map'等.all函数? [来源](http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each) – Gunderson
你是对的。我试图避免使用速记$$,但转换失败。我已经更新了这个问题。 – Machtyn