打破了量角器.filter()或.map()循环

pel*_*can 1 selenium browser-automation webautomation protractor e2e-testing

我正在使用量角器和黄瓜框架; 如何突破.filter或.map循环?如果我发现匹配,我不想再继续迭代!

Page.prototype.getElementByKey = function (key) {
      var foundElement = null;
      return someElement.all(by.css('.someClass')).map(function (rawItem, index) {
        var itemObject = new ItemObjectClass(rawItem);
        return itemObject.getItemKey().then(function (foundItemKey) {
          var matched = String(foundItemKey).trim() === String(key).trim();

         console.log(' Matched: { ' + matched + ' }  index {'+index+'}');
          //if we have a match break out of the .filter function
          if (matched) {
            foundElement = itemObject;
            throw new Error("Just our way of breaking out of .filter() above");
          }
        });
      }).then(function () {
        //callback
        throw new Error('\n!!!!!Callback should not be called; 
       this means that we could not find an element that matched the passed in key above');
      }, function (error) {
        //error
        console.log('\n*******************errorCallback was called; '+error);
        return foundElement;
      });
    };
Run Code Online (Sandbox Code Playgroud)

上面的代码找到了元素但是继续迭代直到结束,而不是在匹配时停止并通过调用errorCallback函数来中断.

鉴于.map函数返回" 一个解析为map函数返回的值数组的promise " http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map,我正在利用如果承诺无法解决,承诺将调用其errCallback这一事实.

通过抛出一个假的错误,应该调用errorCallback,从而打破.map循环.

不幸的是,它成功抛出错误但继续循环而不是爆发.我知道因为当我

console.log("boolean"+ matched +"和index"+ index);

我明白了:

matched: false index: 0
matched: false index: 1
matched: true index 2 //it should have stopped here since matched = true
matched false index 3 // this should NOT have printed
Run Code Online (Sandbox Code Playgroud)

如此突破不起任何想法?

Flo*_* B. 6

你要返回一个元素,所以.reduce最好.

这是一个用法示例,用于返回文本为"mylink"的第一个链接:

var link = element.all(by.css('a')).reduce(function (result, elem, index) {
    if(result) return result;

    return elem.getText().then(function(text){
        if(text === "mylink") return elem;
    });

}).then(function(result){
    if(!result) throw new Error("Element not found");
    return result;
});
Run Code Online (Sandbox Code Playgroud)