Due to a weird API, I need to call asynchronous recursive function in loop and getting result in angularJS. Below is example of my situation.
We have task lists, each Task may have none, one or more Sub Tasks Each Sub Tasks may further have none, one or more Sub Tasks I need to get all Tasks and Sub Tasks in a single array of objects The problem is for getting the list of Sub Tasks of a Task, we need to call async API. Due to async in nature of API, I was not able to get all result
//We have task lists
allTasks = fromSomeOtherFuncion();
$scope.loadSubTask = function () {
var deferred = $q.defer();
for (var j = 0; j < allTasks.length; j++) {
for (var k = 0; k < allTasks[j].subtasks.length; k++) {
$scope.fetchTaskByTaskID(allTasks[j].subtasks[k].id, deferred);
}
}
return deferred.promise;
};
$scope.fetchTaskByTaskID = function (id, deferred) {
if (!deferred) {
deferred = $q.defer();
}
var client = window.client;
client.tasks.findById(id, {
opt_fields: 'id,name,memberships,subtasks',
}).then(function (response) {
if (response.subtasks.length > 0) {
for (var m = 0; m < response.subtasks.length; m++) {
$scope.fetchTaskByTaskID(response.subtasks[m].id, deferred);
}
}
else {
deferred.resolve(response);
return deferred.promise;
}
});
};
//Then I called the function
$scope.loadSubTask().then(function (subtasks) {
//I need here all Tasks+SubTasks+SubSubTasks..., which I am not getting
});