title: How to avoid HTTP-request race conditions in JavaScript/AngularJS?
body: <p>I'm using JavaScript in combination with AngularJS and recently went into some issues with HTTP-request race conditions.</p>
  
  <p>For demo purposes i'll try to simplify the problem a bit:
  Say you have several scope.$watch listeners up and running and some of them may trigger from time to time some REST-calls.</p>
  
  <p>Now there may be some logic going on withing these listeners triggering each other and in the end you end up with two REST-calls being made to the same url with different parameters while the parameters of the first call are obsolete in the meantime (all of this happens within some milliseconds). Both callbacks are essentially the same as well and will overwrite some variable "result" in my controller or whatever.</p>
  
  <p>As long as both requests take the same amount of time on the server they will return in the same order and therefore the result of the second calls will overwrite the one of the first call and everything is fine.
  However, of course we can not guarantee that to happen, so we end up with an ugly race condition here.</p>
  
  <p>So, now i'm wondering if there are any "best-practices" or "design-patterns" or other "tricks" to avoid these kind of problems in the first place.</p>
  
  <p>I've read about canceling ajax requests and tried that solution - unfortunately it isn't as easy in AngularJS as it is in pure jQuery, plus the structure of my application didn't really favor this kind of solution.
  Yet, even if i go with ajax canceling i would still be interested in a corresponding design pattern, since canceling pending requests isn't always what you want to do in you application.</p>
  
  <p>For my project a working solution was to remember what the last request parameters were whenever i did such a problematic call and only resolve the result if and only if the last used request parameters were equal to the request parameters used for the given call, so in other words:</p>
  
  <ul>
  <li>call f with param=1
  --> remember 1</li>
  <li>call f with param=2
  --> remember 2, hence overwrite 1</li>
  <li>2nd call returns
  --> check if used param (2) equals last used param (2) --> resolve</li>
  <li>1st call returns
  --> check if used param (1) equals last used param (1) --> don't resolve</li>
  </ul>
  
  <p>Well, this worked for my program in my context, but of course it doesn't always apply. Sometimes you need to have the option to make two calls of the same kind with two different parameters at the same time without your code rejecting it...</p>
  
  <p>So again: do you guys know any good solutions to this problem in the first place ? Enlight me please... :D</p>