获得量角器承诺,变量和结果同步

时间:2016-05-25 16:27:10

标签: javascript protractor

好的,我有这段代码,我在尝试写作时失败了。我想要做的是确保传递给函数的索引在页面上可用元素的范围内。并且,如果是,则传回元素引用。

假设我有以下内容:

<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);
}

上述情况将失败,因为计数不是真正的计数,而是承诺。

所以,我尝试过以各种方式修改它。我认为成功的那个如下:

// 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块抛到了可能的功能中,但它不会&#34;看到&#34;索引。

(每当我想到我已经想到这一点时,我都不会。感谢您提供任何帮助!)

更新

根据以下建议,我尝试将代码修改为:

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未定义。此外,在错误消息中,我甚至没有获得计数值。

> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through 

2 个答案:

答案 0 :(得分:1)

我认为你必须使用javascript闭包才能实现它。

试一试:

var count = element(by.css('li')).count().then(function(c){
    return function(){
        return c
    }   
});

var value = count();

您的值应该在“值”变量中。

PS:我现在没有用于测试此代码的量角器环境

答案 1 :(得分:1)

这是我如何解决它。

function getRow(index) {
    var count = $$('li').count();

    var test = function(index, count) {
        // Ensure a parameter has been passed.
        if (index == undefined) {
            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);
        }
    });

    count.then(function(count) {
        test(index, count);
    }

    return $$('li').get(index);
}

我不确定为什么会这样,而我以前的尝试也没有。好吧,除了我抽象函数并允许自己以干净的方式传入索引。