Skip to content

Instantly share code, notes, and snippets.

@pablotdl
Last active August 29, 2015 14:22
Show Gist options
  • Save pablotdl/e7aff93b01a149b2d3af to your computer and use it in GitHub Desktop.
Save pablotdl/e7aff93b01a149b2d3af to your computer and use it in GitHub Desktop.
Avoid using $q unless necessary. Most async methods already return a promise
/**
* This service showcases when to use $q to return promises and when it's not necessary'
*/
angular.module('sample').factory('sampleService', ['$q', '$http', function ($q, $http) {
var service = {};
// Use constants, don't do this
var url = 'https://api.github.com/users/pablotdl/repos';
/**
* This service uses $q to wrap an $http call to the Github API
*/
service.getRepos = function () {
var deferred = $q.defer();
$http.get(url)
.success(function (data) {
// Assuming $http will deserialize the JSON response automagically
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error)
});
return deferred.promise;
}
/**
* This service returns the promise returned by $http directly
*/
service.getReposProper = function () {
// Unlike then, success callbacks cannot be chained
// Then callbacks will be executed one after the other.
return $http.get(url)
//The then callback will receive a response... we are only interested in the data property
.then(_.property('data'));
}
/**
* In this example, we want to return the URL we are using, but want to do so maintaining
* the promise pattern
*/
service.getUrl = function () {
var deferred = $q.defer();
deferred.resolve(url);
return deferred.promise;
}
/**
* And this is how it should be done
*/
service.getUrlProper = function () {
return $q.when(url);
}
return service;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment