量角器承诺生成的数组会覆盖先前的值

时间:2015-09-08 21:36:06

标签: angularjs promise protractor

我有角度ui网格,我试图从其细胞中获取值。这是表格中的列表

  id name
   1 AUSTRIA
   2 BELGIUM
   3 BULGARIA
   4 CROATIA
   5 CZECH REPUBLIC

这是我运行的代码:

element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
    for (var i = 0; i < items.length; i++) {
        var country = <any>{}; //typescript code

        self.gridTestUtils.dataCell('grid1', i, 0).getText().then(
        function (valueId) { 
            country.id = valueId 
        });

        self.gridTestUtils.dataCell('grid1', i, 1).getText().then(
        function (valueName) {
            country.name = valueName;
            self.countryList.push(country)
            console.log(self.countryList)                                
        });
    }
});

这是结果

[ { id: 1, name: 'AUSTRIA' }]

[ { id: 1, name: 'BELGIUM' }, 
{ id: 1, name: 'BELGIUM' }]

[ { id: 1, name: 'BULGARIA' },
  { id: 1, name: 'BULGARIA' },
  { id: 1, name: 'BULGARIA' } ]

[ { id: 1, name: 'CROATIA' },
  { id: 1, name: 'CROATIA' },
  { id: 1, name: 'CROATIA' },
  { id: 1, name: 'CROATIA' } ]

[ { id: 1, name: 'CZECH REPUBLIC' },
  { id: 1, name: 'CZECH REPUBLIC' },
  { id: 1, name: 'CZECH REPUBLIC' },
  { id: 1, name: 'CZECH REPUBLIC' },
  { id: 1, name: 'CZECH REPUBLIC' } ]

我希望结果如下:

[ { id: 1, name: 'AUSTRIA' }]

[ { id: 1, name: 'AUSTRIA' }, 
{ id: 1, name: 'BELGIUM' }]

[ { id: 1, name: 'AUSTRIA' },
  { id: 1, name: 'BELGIUM' },
  { id: 1, name: 'BULGARIA' } ]

[ { id: 1, name: 'AUSTRIA' },
  { id: 1, name: 'BELGIUM' },
  { id: 1, name: 'BULGARIA' },
  { id: 1, name: 'CROATIA' } ]

[ { id: 1, name: 'AUSTRIA' },
  { id: 1, name: 'BELGIUM' },
  { id: 1, name: 'BULGARIA' },
  { id: 1, name: 'CROATIA' },
  { id: 1, name: 'CZECH REPUBLIC' } ]

我的代码出了什么问题?我应该做什么,我期待数组

1 个答案:

答案 0 :(得分:0)

问题是你的循环中的i会随着循环的进行而发生变化,而在你的异步调用中,你正在使用i并获得一个承诺,但它只是一个参考,因此,当promises得到解决时,将使用循环的最后一个值来引用变量。解决方法是创建IIFE

element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
    for (var i = 0; i < items.length; i++) {
        var country = <any>{}; //typescript code

        (function (i, country) {
            self.gridTestUtils.dataCell('grid1', i, 0).getText().then(function (valueId) {
                country.id = valueId;
            });

            self.gridTestUtils.dataCell('grid1', i, 1).getText().then(function (valueName) {
                country.name = valueName;
                self.countryList.push(country)
                console.log(self.countryList)
            });
        })(i, country);
    }
});