title: Using protractor with loops
body: <p>Loop index (<code>i</code>) is not what I'm expecting when I use Protractor within a loop. </p>
  
  <p><strong>Symptoms:</strong> </p>
  
  <blockquote>
    <p>Failed: Index out of bound. Trying to access element at index:'x', but there are only 'x' elements</p>
  </blockquote>
  
  <p>or</p>
  
  <blockquote>
    <p>Index is static and always equal to the last value</p>
  </blockquote>
  
  <p><strong>My code</strong></p>
  
  <pre><code>for (var i = 0; i &lt; MAX; ++i) {
    getPromise().then(function() {
      someArray[i] // 'i' always takes the value of 'MAX'
    })
  }
  </code></pre>
  
  <p>For example:</p>
  
  <pre><code>var expected = ['expect1', 'expect2', 'expect3'];
  var els = element.all(by.css('selector'));
  for (var i = 0; i &lt; expected.length; ++i) {
    els.get(i).getText().then(function(text) {
      expect(text).toEqual(expected[i]); // Error: `i` is always 3. 
    })
  }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>var els = element.all(by.css('selector'));
  for (var i = 0; i &lt; 3; ++i) {
    els.get(i).getText().then(function(text) {
      if (text === 'should click') {
        els.get(i).click(); // fails with "Failed: Index out of bound. Trying to access element at index:3, but there are only 3 elements"
      }
    })
  }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>var els = element.all(by.css('selector'));
  els.then(function(rawelements) {
    for (var i = 0; i &lt; rawelements.length; ++i) {
      rawelements[i].getText().then(function(text) {
        if (text === 'should click') {
          rawelements[i].click(); // fails with "Failed: Index out of bound. Trying to access element at index:'rawelements.length', but there are only 'rawelements.length' elements"
        }
      })
    }
  })
  </code></pre>