AgmLauncher AgmLauncher - 6 months ago 9x
Javascript Question

Patterns for handling the response of only the latest async request in Angular?

Have discovered a bug with respect to debounced input and handling responses.

I have a search input that queries the server as you type. I put a debounce on it set to 300ms. However, sometimes there's some odd behavior:

User types "ab", waits 300ms, types "c" before that first request resolves. In the search bar they see "abc", but there are now two network requests. Sometimes the second request ("abc") resolves first, then the first request ("ab") resolves and overwrites the results list. So the user sees a list of results for "ab", but the search input has "abc".

This seems like less of an issue of debounce per se, and more along the lines of finding a way to discard "old" promises so that they can be ignored when they resolve.

So for example - what I want

  • types

  • send request "ab"

  • types

  • send request "abc"

  • "abc" returns response, handle promise resolution

  • "ab" returns response, ignore promise

Are there any common patterns/approaches for this sort of thing in Angular? It sounds like it would be a common issue.

E.g "Resolve only the latest promise that was created"?


This is a perfect use-case to introduce RxJS, Angular 2 has default support for RxJS. However in Angular 1 it's also possible to use this library, take a look at the official rx.angular.js library over here.

If you include this library you should be able to solve your problem as follows:


<input type="text" ng-model="search">


observeOnScope($scope, 'search')
  .safeApply($scope, function (data) {
     $ = data;

function search() {
  return rx.Observable.fromPromise($http({ ... }));

Edit: a more in depth article can be found over here