问题
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