Skip to content Skip to sidebar Skip to footer

Return A Promise That Promises To Throw Error

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,

Solution 1:

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 matchreturn $q.reject(newError("no matching index"));
       }
   }

Documentation here.

Solution 2:

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.

Post a Comment for "Return A Promise That Promises To Throw Error"