量角器 - 如何将一组承诺的结果放入另一个数组

2022-01-16 00:00:00 arrays angularjs protractor javascript

我从这段代码中得到了一系列承诺:element.all(by.repeater('unit in units')),我发现很难将数据放入另一个数组:

I got an array of promises from this code: element.all(by.repeater('unit in units')), and I am finding it really difficult to get the data into another array:

element.all(by.repeater('unit in units')).then(function (arr) {
    var items = [];

    for (var i = 0; i < arr.length; i++) {
      arr[i].getText().then(function(text) {
        items.push(text);
      });
    }

   //PROBLEM ITEMS is Empty
   console.log(items);
});

推荐答案

设法以更简单的方式获得相同的结果,避免使用 Q 和中继器.使用内置地图就可以了.

Managed to get the same result on a simpler way avoiding using Q and the repeater. Using the inbuilt map does the trick.

var tabs = element.all(by.css('.unitTabs li a')).map(function (elm) {
    return elm.getText();
});

tabs.then(function (result) {
    var sorted = _.sortBy(result, function (name) { return name; });
    for (var i = 0; i < result.length; i++) {
        expect(result[i]).toBe(sorted[i]);
    }
});

相关文章