2016-12-20 27 views
1

我有一个函数,它正确检索元素的索引,哪个文本===“检查”。它清楚地印在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); 

所以,在这里我已经尝试的功能,这guaratees任何承诺的决心里面的init资源的价值,但它不工作,并返回null。

我认为,我在getIndex()函数中有错误,也许,我已将return opertor放置在错误的地方,但我需要帮助。我完全不知道如何使它工作。请帮助。

回答

2

你是过于复杂的问题,使用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类的定位器 - 它是一个纯粹的技术角度特定类,它不会给你的定位器带来意义。

+0

非常有趣,但我得到'undefined'valuse。我很抱歉,如果我的问题很蠢,我刚开始使用JS进行测试。 – SanchelliosProg

+0

@SanchelliosProg啊,nono,我很笨,忘了'return'。请再试一次。 – alecxe

+0

你是我的SUPERHERO !!!!!!!!你救了我的生命))))非常感谢你! – SanchelliosProg

1

我目前还无法对它进行调试,但这应该工作:

function getIndex() { 
    return element 
      .all(by.css(".palette__item.ng-scope>span")) 
      .then((colorList) => { 
       // get text for all elements 
       return Promise.all(colorList.map((el) = el.getText())); 
      }) 
      .then((colorList) => { 
       // we need both text and index 
       return colorList.map((el, ind) => [el, ind]) 
       // but just the elements with text "check" 
           .filter((elArr) => ellArr[0] == 'check') 
       // at this point we can throw away the text and just use the index 
           .map((elArr) => elArr[1]); 
      }) 
} 

您的基本问题是,你混功能,即回报的承诺,与其他迭代器的功能。所以当你最终致电return时,你完全失去了承诺背景。

1

一些事情: 对于初学者,您初始化承诺之外的变量,但在承诺中分配变量的值。这非常好,但请看看您向我们展示的示例中console.log()的位置。如果您将console.log语句保留在最底层,那么在您的承诺解析之前它将最可能被执行,因此变量res的值将为空。

您是否尝试在承诺内注销res的值?

回到getIndex函数...为什么在forEach函数中使用promise?您是否尝试过这样做,而不是执行以下操作:

function getIndex() { return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) { colorList.forEach(function (elem, index) { var temp = elem.getText() if (temp == "check") { console.log(index); return index }); }); }); }

这是所有我可以和你在这个岗位所提供的信息量建议。从中获得的关键教训是更好地理解异步代码与异步代码的区别。