Skip to content

Instantly share code, notes, and snippets.

@toddmotto
Created June 10, 2014 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddmotto/9ee0abc5c8120e010a27 to your computer and use it in GitHub Desktop.
Save toddmotto/9ee0abc5c8120e010a27 to your computer and use it in GitHub Desktop.
XHR wrapper for AngularJS $http
/**
* @name xhr
* @desc Dynamic $http/$q
* @param {String} [type] HTTP method
* @param {Array} config Array of config to be called with .apply()
* @private
* @returns {Object} deferred.promise
*/
var xhr = function (type, config) {
if (!config && angular.isArray(type)) {
config = type;
type = 'get';
}
var deferred = $q.defer();
$http[type].apply($http, config)
.success(function (data) {
deferred.resolve(data);
})
.error(function (reason) {
deferred.reject(reason);
});
return deferred.promise;
};
@Samstiles
Copy link

Haven't used $q much personally. Could you provide an example of this being used? :)

@toddmotto
Copy link
Author

Use $q for promises/defers, but it's also a nicer way (IMO) to resolve the $http (which would return a promise) but mixing with $q provides us the pure promise Object and data rather than HTTP crap. We can also use $q.all() to create an Array of promises too:

$q.all([
  promise1.then(something),
  promise2.then(somethingElse)
])
.then(function(data) {
  // do something with `data`
});

More: https://docs.angularjs.org/api/ng/service/$q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment