AngularJS - How to cancel a promise?

Let's say I have an input text box (more like a Google search box) that, when changed, calls up a query and shows some results.

For example,

Enter the type Dog at 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 Dog . My model would end up with DO results, even if I typed Dog .

To do this, I need to cancel or interrupt current current requests if I continue to type characters. Thus, my model is changed only upon final request.

My input is as follows:

 <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; }); } 
+8
javascript angularjs promise deferred
source share
3 answers

Usually people use ng-model-options={debounce: 100} .

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

In any case, you can refuse the promise.

+4
source share

I think you want to use the debounce technique in this case?

cm.:

+1
source share

Example: $q.reject(response);

Although technically I believe that the aforementioned commentator is true, you are actually rejecting the promise and not breaking it.

0
source share

All Articles