1

I'm trying to understand how promises works in js. I have the following protractor test:

fieldConstraintsList.forEach(function(constrains){

     // WARNING... or not??
     var input = element(by.model(constrains.model)); //Getting input element

     input.getAttribute('value').then(function(initialValue){

           // Do validation stuff....

           //WARNING... or not??
           input.clear();//Restore initial value
      });
});

This receive a list of constraints to apply to a form with a model that identify each input. As you can see, a promise is executed inside the loop so, as long as there is a reference to the input variable that is declared outside of the promise, I expect a different behavior (see edit section later).

Some one can gives me some tips or reference??

Thanks in advance.

EDITED

I was expecting a behavior like this: supposing constrains has length 2, 2 elements are created: input = A and input = B, and, again, 2 promises are created promise(A) and promise(B). As long as the promises are not immediately resolved (or yes???) when promise(A) is resolved then input = B and B should be the one to be clear and not A.

In short this is what I have been expecting: input = A => input = B => promise(A) => promise(B)

The actual behavior of the applications that is annoying me is: input = A => promise(A) => input = B => promise(B).

RoberMP
  • 1,306
  • 11
  • 22
  • So you are asking why it is working, instead of.. why something is not working? Well, that's new :D – Poul Kruijt Mar 10 '16 at 11:04
  • 1
    I don't understand what _"referencing external variable"_ has to do with the fact that you use a promise. And what _"strange behavior"_ did you expect? – a better oliver Mar 10 '16 at 11:11
  • This is called __closures__ and is a fundamental property of some languages including JavaScript. See http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Benjamin Gruenbaum Mar 10 '16 at 11:51

0 Answers0