Welcome to the world of asynchronous calls.
If you call an asynchronous call inside getDefinitions (from definitonsService), you should assume that getDefinitions () is also asynchronous. This means that you cannot just return defs.
When you print defs before returning it, the asynchronous service call has not yet completed.
defs should also be an object of promise. Then you can return it the same way you do, but the method calling it should also use it with .then (function (defs) ...
Or in code form:
function getDefinitions() { var defs = $q.defer(); definitionsService.get().$promise.then(function(data) { defs.resovle(data); }); return defs.promise; };
And anyone who calls getDefinitions() :
getDefinitions().then(function(defs) {
The answer to the question after editing:
The problem is again related to the asynchronous nature inside the getAccounts method. utilitiesService.detail is an asynchronous method. This way you are actually assigning promises, not values, to the [i] .detail accounts.
Since each account entails an asynchronous call, using $ q.all seems like a good idea:
var promises = []; for (var i = 0; i < accounts.length; i++) { promises.push(utilitiesService.detail(accounts[i])); } $q.all(promises).then(function(values)){
remember - receiving a promise is synchronous. Getting a value that promises ... well, promises to get you is asynchronous.
source share