How to wait for element.all().each() to resolve before proceeding

时间:2015-11-18 21:04:13

标签: javascript selenium promise protractor end-to-end

I'm trying to iterate through a list of elements to find if any one of them has a particular value as it's getText() value.

My problem is that my test is not executing in the order I've laid it out.

I've read a bunch about queuing and Promise resolution, but I don't understand how it affects my current scenario.

Here is what I'm doing:

it('should find apps by name', function() {
    var exists = false;

    element.all(by.repeater(‘item in list’).each(function(elem) {
        elem.getText().then(function(text) {
            if(text == 'foo') 
                exists = true;
            return exists;
        }).then(function(exists) {
            console.log('interim value: ' + exists);  // This appears after
        });
    });

    console.log('final status: ' + exists);   // This appears in the console first
})

Any insight into how I can determine what I want the value of my boolean to be before I log it at the end would be greatly appreciated.

1 个答案:

答案 0 :(得分:1)

量角器属于异步性质 - 一切都是承诺,由Control Flow控制:

  

WebDriverJS(以及Protractor)API完全是异步的。所有   函数返回承诺。

     

WebDriverJS维护一个待处理的承诺队列,称为控件   流程,以保持执行有序。

换句话说,不要指望代码从上到下工作。

由于您需要一个布尔值来指示存在所需的元素 - each()不是一个好选择 - 它只会将函数应用于每个元素。请改用reduce()

var exists = element.all(by.repeater("item in list")).reduce(function(acc, elem) {
    return elem.getText().then(function(text) {
        return !acc ? text === 'foo' : acc;
    });
}, false);