如何在继续之前等待 element.all().each() 解决

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

我正在尝试遍历元素列表以查找其中是否有任何一个具有特定值,因为它是 getText() 值。

我的问题是我的测试没有按照我安排的顺序执行。

我已经阅读了很多关于排队和 Promise 解析的内容,但我不明白它如何影响我当前的场景。

这是我正在做的事情:

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

任何关于我如何确定我希望我的布尔值是什么的见解在之前我将不胜感激。

Protractor 具有异步性质 - 一切都是承诺并由 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.

换句话说,不要期望代码从上到下运行。

因为您需要一个布尔值来指示有一个所需的元素 - 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);