Search code examples
javascriptajaxangularjsangularjs-service

Ensure the proper order of subsequent HTTP ajax calls in AngularJS


Assume we have a super simple search form with autocomplete which triggers a $http.get() request on keyup/keypress:

<input type="text" ng-model="keyword" ng-change="makeRequest()">

and

$scope.makeRequest = function() {
   $http.get(url).then(function(res) {
      // update the typeahead list here.
   });
}

What is the easiest way to maintain order in which the responses are being passed in? Due to a varying latency earlier results often come last which confuses user. I'm looking for something order than a straight debounce which would prevent a request from being made under a certain keystroke interval.


Solution

  • You can keep track of the latest request and ignore responses unless it's from the latest...

    var latestRequest = 0;
    $scope.makeRequest = function() {
       var thisRequest = ++latestRequest;
       $http.get(url).then(function(res) {
          if (thisRequest === latestRequest) {
            // update the typeahead
          }
       });
    }