Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to cancel a promise? [duplicate]

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;
    });
}
like image 446
Matias Cicero Avatar asked Nov 03 '15 18:11

Matias Cicero


2 Answers

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

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

anyway you can reject promise.

like image 69
Errorpro Avatar answered Oct 04 '22 06:10

Errorpro


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

see:

  • https://docs.angularjs.org/api/ng/directive/ngModelOptions
  • http://ilikekillnerds.com/2014/12/increasing-angular-performance-by-debouncing-your-ng-model-updates/

    <input type="text"
       class="form-control" 
       data-ng-model="query" 
       data-ng-change="ctrl.search(query)" 
       placeholder="Search" 
       ng-model-options="{ debounce: { 'default': 500,  'blur': 0 } }"    
    />
    
like image 45
house9 Avatar answered Oct 04 '22 07:10

house9