How would you make an Angular service return a promise?

Technology CommunityCategory: AngularJSHow would you make an Angular service return a promise?
VietMX Staff asked 3 years ago
Problem

Write a code snippet as an example

To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:

angular.factory('testService', function($q) {
  return {
    getName: function() {
      var deferred = $q.defer();

      //API call here that returns data
      testAPI.getName().then(function(name) {
        deferred.resolve(name);
      });

      return deferred.promise;
    }
  };
});

The $q library is a helper provider that implements promises and deferred objects to enable asynchronous functionality.