好吧,我正在尝试编写这段代码,但失败了。我想要做的是确保传递给函数的索引位于页面上可用元素的范围内。如果是,则传回元素引用。
假设我有以下内容:
<ul>
<li>First row</li>
<li>Second</li>
<li>Third</li>
</ul>
所以,我有这个功能:
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);
}
上面的代码将会失败,因为 count 并不是真正的 count,而是一个 promise 。
所以,我尝试了各种方式修改它。我认为会成功的如下:
// 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; });
我很沮丧,并尝试将整个 if block 放入 thenable 函数中,但它不会“看到”索引。
(每次我以为我已经解决了这个问题,但实际上却没有。感谢您提供的所有帮助!)
更新:
按照下面的建议,我尝试将代码修改为:
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()
block 中,index
未定义。另外,在错误消息中,我什至没有得到计数值。
> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through
最佳答案
我认为你必须使用 javascript 闭包才能实现它。
尝试一下:
var count = element(by.css('li')).count().then(function(c){
return function(){
return c
}
});
var value = count();
您的值应该位于“value”变量中。
PS:我现在没有 Protractor 环境来测试此代码
关于javascript - 同步 Protractor Promise、变量和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442902/