I am facing an issue with my service where the success function in the controller is not being executed immediately. The compiler is parsing the lines after the service call, which is not the desired behavior. In debug mode, I noticed that there is a delay of around 10 milliseconds before my data is available.
.factory('myService', ['$http', '$q', function($http, $q){
var deferObject,
myMethods = {
getDepartments: function(d) {
console.log("Reached here");
var allDepartments=[];
var promise=$http.get("http://localhost:8087" + "/projects/"+d );
var deferObject = deferObject || $q.defer();
console.log("Reached here too");
promise.then(
// OnSuccess function
function(answer){
console.log("Reached here as well");
// This code will only run if we have a successful promise.
deferObject.resolve(answer);
var setDepartments = new Set();
for (var i = 0; i < answer.data.length; i++) {
setDepartments.add(answer.data[i].department);
}
setDepartments.forEach(function (value) {
var department = {name: value};
allDepartments.push(department);
});
console.log(allDepartments);
return allDepartments;
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
deferObject.reject(reason);
});
return allDepartments;
},
getData: function(d) {
var promise=$http.get("http://localhost:8087" + "/projects/"+d )
var deferObject = deferObject || $q.defer();
promise.then(
// OnSuccess function
function(answer){
// This code will only run if we have a successful promise.
deferObject.resolve(answer);
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
deferObject.reject(reason);
});
return deferObject.promise;
}
};
return myMethods;
}]);