Search code examples
javascriptangularjspromisedeferred

AngularJS - How to cancel a promise?


Let's say I have an input text field (more like the Google search field) which, when changed, will trigger a request and show some results.

For instance,

Let's type in Dog in the input:

typed D -> Calls ctrl.search('D') -> Makes a request -> Changes model when success
typed DO -> Calls ctrl.search('DO') -> Makes a request -> Changes model when success
typed DOG -> Calls ctrl.search('DOG') -> Makes a request -> Changes model when success.

Now, let's say that the DO request responds later than the DOG one. My model would end up with the DO results, even if I typed DOG.

For that, I need a way to cancel or abort current ongoing requests if I keep on typing characters. That way, my model is only changed by the final request.

My input looks like the following:

<input type="text" class="form-control" data-ng-model="query" data-ng-change="ctrl.search(query)" placeholder="Search" />

Here is my searchCtrl.js:

var search;
var language;
var _this;

var SearchCtrl = function (searchService, lang)
{
     search = searchService;
     langauge = lang;
     _this = this;
}

SearchCtrl.prototype.search = function (text)
{
    var promise = search.language(language)
                  .facet('characters')
                  .highlight('quotes')
                  .query(text);

    promise.then(function (response) {
         if(!response) return;
         _this.total = response.total;
         _this.count = response.found;
         _this.result = response.data;
    });
}

Solution

  • Usually for this case people use ng-model-options={debounce: 100}.

    https://docs.angularjs.org/api/ng/directive/ngModelOptions

    anyway you can reject promise.