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

徘徊边缘 提交于 2019-12-22 13:03:01

问题


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:


Protractor is of an asynchronous nature - everything is a promise and controlled by a Control Flow:

WebDriverJS (and thus, Protractor) APIs are entirely asynchronous. All functions return promises.

WebDriverJS maintains a queue of pending promises, called the control flow, to keep execution organized.

In other words, don't expect the code to work from top to bottom.

Since you need a single boolean value indicating that there is a desired element - each() is not a good choice - it would just apply a function to every element. Use reduce() instead:

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


来源:https://stackoverflow.com/questions/33790336/how-to-wait-for-element-all-each-to-resolve-before-proceeding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!