Background
I am making a angularJS app
I have an object called a Map. The Map has an array of Transforms IDs.
I need to fetch each transform in the Maps's array, then save these to an array of Transforms instead of an array of Transform IDs. So far, I have this done, except calling the function at the correct time.
I want to call a function: doStuffWithTransformArray
using the completed array.
Question
How do I call a function only when the array is finished being filled?
Current Code (this only works sometimes)
$scope.makeTransformArray = function () {
$scope.transforms = [];
$scope.map.transforms.forEach(function(eachTransformID, index) {
Transform.get({uuid: eachTransformID.uuid}, function(transformResult) {
$scope.transforms[index] = transformResult;
if ($scope.transforms.length == $scope.map.transforms.length) {
$scope.doStuffWithTransformArray($scope.transforms);
return;
}
});
});
}
Problem
This current code will work only when the last Transform in the Map's array finishes last.
It will call the doStuffWithTransformArray
twice if when the array is filled like this: (5) [y, y, y, empty, y]
The fourth one is not yet filled but the fifth finished.
EDIT 1
Here is my transform Service:
angular.module('serviceregistryApp')
.factory('Transform', function ($resource) {
var url = 'api/v1/transform/:uuid';
return $resource(url, {transform: '@transform', uuid: '@uuid'}, {
'save': {method: 'POST', headers: {"Authorization": "ABC"}},
'delete': {method: 'DELETE', headers: {"Authorization": "ABC"}},
'post': {method: 'POST', headers: {"Authorization": "ABC"}},
'get': {
method: 'GET', isArray: false,
headers: {
"Authorization": "ABC"
}, url: "api/v1/transform/:uuid",
transformResponse: function (data) {
return JSON.parse(data);
}
}
});
});
EDIT 2
As suggested in the comments, this seems to work, but I find it kinda ugly.
$scope.makeTransformArray = function () {
$scope.transforms = [];
var counter = 0;
$scope.map.transforms.forEach(function(eachTransformID, index) {
Transform.get({uuid: eachTransformID.uuid}, function(transformResult) {
$scope.transforms[index] = transformResult;
counter = counter + 1;
if (counter == $scope.map.transforms.length) {
$scope.doStuffWithTransformArray($scope.transforms);
return;
}
});
});
}