I am having a recursive function which works well and get all the results that I need. once it get's into the second "then" block it logs all the results. However the "return deferred.promise" happens before the data has been loaded, which kind of confuse me as the promise will only be resolved after the data has been loaded. If I move the return deferred.promise up in the 2nd then block, the consuming code tell me this method is not thennable. kKind of confused which part I am missing, any help will be much appreciated.
The code
function getUserGroups(groups, nextLink) {
var deferred = $q.defer();
var intermediaryGroupResult = groups;
var endpoint = '';
if (nextLink != '' && nextLink !== undefined) {
endpoint = nextLink;
} else {
endpoint = config.baseGraphApiUrl + "me/memberOf?$select=id,displayName,securityEnabled";
}
(function (intermediaryGroupResult) {
$http.get(endpoint).then(function (result) {
var dataNextLink = result.data['@odata.nextLink'];
var resultsFromGraph = result.data.value;
for (var i = 0; i < resultsFromGraph.length; i++) {
intermediaryGroupResult.push(resultsFromGraph[i]);
}
if (dataNextLink != '' && dataNextLink !== undefined) {
getUserGroups(intermediaryGroupResult, dataNextLink)
} else {
console.log('groups', intermediaryGroupResult);
return intermediaryGroupResult;
}
}).then(function (allGroups) {
console.log('all groups', allGroups)
deferred.resolve(allGroups);
});
})(intermediaryGroupResult);
return deferred.promise;
}