Promises inside for loops

2019-05-04 19:13发布

问题:

I'm struggling with this:

  • Click a button to get a set of data
  • Check the number of rows returned is what I'm expecting
  • I need to run this 10 times, each time, I'm expecting a different number of rows

The code snippet below doesn't work because 'i' isn't what I'm expecting. How can I make this work?

for (var i = 0; i < subElements.length; ++i) {
    element(by.id('get-data')).click();

    // Check users returned
    element.all(by.id('users')).map(function (elm) {
        return elm;
    }).then(function (users) {
        expect(users.length).toBe(expectedRecords[i]);
        // Some more checks to be added later
    });
}

回答1:

What about:

for (var i = 0; i < subElements.length; ++i) {
    element(by.id('get-data')).click();

    var count = element.all(by.id('users')).count();
    expect(count).toBe(expectedRecords[i]);
}

As long as you aren't accessing i in a then, it will be what you want, otherwise i will the the last value in your loop and you'll need closure.

EDIT: see Using protractor with loops



回答2:

Using bluebird

var Promise = require('bluebird');

it('my test', function(done){
  var promises = subElements.map(function(subElm, i){
    return element(by.id('get-data')).click()
      .then(function(){
        // Check users returned
        return element.all(by.id('users')).map(function (elm) {
          return elm;
        })
      })
      .then(function(users) {
        expect(users.length).toBe(expectedRecords[i]);
      });
  });

  Promise.all(promises).nodeify(done);
})