Skip to content

Instantly share code, notes, and snippets.

@wandroll
Created April 17, 2016 13:04
Show Gist options
  • Save wandroll/0f6df6dfb82e717b656ee7b0c7521d85 to your computer and use it in GitHub Desktop.
Save wandroll/0f6df6dfb82e717b656ee7b0c7521d85 to your computer and use it in GitHub Desktop.
Data Service Factory using $q
/**
* dataservice Factory
* @namespace Factories
* @author Wandrille Verlut <wandrille.verlut@gmail.com>
*/
(function() {
'use strict';
angular
.module('app')
.factory('dataservice', dataservice);
dataservice.$inject = ['$http', '$q', 'ELEMENTS_LIST', 'BACKEND_URL'];
/**
* @namespace dataservice
* @desc Manage backend queries
* @memberOf Factories
*/
function dataservice($http, $q, ELEMENTS_LIST, BACKEND_URL) {
return {
getSitesStatus : getSitesStatus
};
/////
/**
* @name getElementsInfos
* @desc Retrieve elements infos from a backend
* @return {Array} a list of elements with their infos
*/
function getElementsInfos() {
var elements = ELEMENTS_LIST;
var countDown = elements.length; // indicates when async calls are done
var deferred = $q.defer(); //creates a promise manager
elements.forEach(function(e) {
// For each element, we ask Backend for infos
$http.get(BACKEND_URL + e.id)
.then(function onBackendResolve(response) {
/** @todo : treat data */
e.infos = response.data;
// if all asyncrhonous calls are done, solve the promise and return the sites
countDown -= 1;
if (countDown === 0) {deferred.resolve(elements);}
}
})
.catch(function onBackendError(response) {
/** @todo : treat anomaly */
e.infos = 'error';
countDown -= 1;
if (countDown === 0) {deferred.resolve(elements);}
});
});
return deferred.promise;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment