0

I am fairly new to using promises, I mostly stick to straight up callbacks. The following code happens to be found in an Angular Service, but that doesn't really matter that much, it's mostly regards how to create a promise that will promise to throw a certain error. So this is how it would happen with callbacks being incorporated, which avoids the problem:

var client = algolia.Client('ApplicationID', 'apiKey');


var indices = {

    users: client.initIndex('users'),
    topics: client.initIndex('topics')

}

return {

   search: function(indexName, searchTerms, cb){
       var index = indices[indexName];

       if(index){
          index.search(searchTerms).then(function handleSuccess(msg){
               cb(null,msg);
            }, function handleError(err){
               cb(err);
            }
       }
       else{
          cb(new Error('no matching index'));
       }

   }

...but changing the above to use pure Promises, I don't know what to do exactly:

var client = algolia.Client('ApplicationID', 'apiKey');

var indices = {

    users: client.initIndex('users'),
    topics: client.initIndex('topics')

}

return {

   search: function(indexName, searchTerms){
       var index = indices[indexName];

       if(index){
          return index.search(searchTerms); //returns a promise
       }
       else{
          //if there is no matching index, how can I return a promise then will return an error?
       }

   }

I know there are different ways to structure the code to avoid the problem at hand but I am curious if there is way to solve it directly.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

2

You just need to return a rejected promise with $q.reject(err):

return {

   search: function(indexName, searchTerms){
       var index = indices[indexName];

       if(index){
          return index.search(searchTerms); //returns a promise
       }
       else{
          // return rejected promise if no match
          return $q.reject(new Error("no matching index"));
       }
   }

Documentation here.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

You could inject $q service and return $q.reject(reason), e.g:

return $q.reject('NO_INDEX');

From $q documentation:

Creates a promise that is resolved as rejected with the specified reason.

Michel
  • 26,600
  • 6
  • 64
  • 69