Search code examples
javascriptangularjsangular-ui-typeahead

Is this javascript promise right?


I am learning AngularJS and trying to implement Angular UI Bootstrap Typeahead in a simple search app using Elasticsearch. I want to use the $http service to load asynchronous results and have not worked much with js promises.

UPDATE: I've done some more learning and testing

I've include the Typeahead as a dependency in my app:

var searchApp = angular.module('searchApp', ['elasticsearch', 'ngSanitize', 'ui.bootstrap']);

Here is the js promise code with the ES Match query mapped to the content.autocomplete field:

this.getSuggestions = function(query) {
var deferred = $q.defer();

esClient.search({
  index: 'bigtestindex',
  body: {
    "query": {
      "match": {
          "content.autocomplete": {
            "query": query,
            "operator": "and"
          }
        }
      },
    "suggest": {
      "text": query,
      "phraseSuggestion": {
        "phrase": {
          "field": "content",
          "direct_generator": [{
            "field": "content",
            "suggest_mode": "popular",
            "min_word_length": 3,
            "prefix_length": 2
          }]
        }
      }
    },
    "size": 5,
    "_source": ["content.autocomplete"]
  }
}).then(function(es_return) {
  deferred.resolve(es_return);
}, function(error) {
  deferred.reject(error);
});

return deferred.promise;

};

With this code, I am trying to achieve the asynchronous results as shown here

Here is the relevant html to display possible matches:

<li ng-repeat="gram in autocomplete.edgengrams">
        <p ng-mousedown="searchForSuggestion()"><small>Search Suggestions: &mdash;</small>{{gram.content}}</p>
  </li>

Solution

  • $http.get() return a promise object already , there is no need to wrap the result in another promise object..

    For your reference https://docs.angularjs.org/api/ng/service/$http#get