miniscem
miniscem

Reputation: 427

Racing Condition: Angular vs Web API & Database

I have an angular service iterates through a list making web api calls that add/modify records in the database (operating on a small record set - max 10 records to update). Since the angular service is returning promises, after the loop completes angular reloads the state with the some of the data updated. Only after I refresh the page is the list fully updated. Everything works as expected; however I think angular is returning before the database completely finishes its operations. Is there a way I can have angular wait to return until all updates are made?

Here is the iterating over the list (has max 10 items) calling the angular service:

for (var i = 0, ii = $scope.Model.permissions.length; i < ii; i++) {
    //if id === 0, it is a new record
    if ($scope.Model.permissions[i].New === true && $scope.Model.permissions[i].Deleted === false) {
        angularService.update($scope.Model.permissions[i]);
    }
}

In the past I have used $q to wait for all promises to be resolved before executing a piece of code:

$q.all([$scope.Model.permissions.$promise,
    $scope.Model.configurations.$promise
]).then(function () {
    $scope.dataLoaded = true;
});

Where each promise would be assigned to the resource call:

$scope.Model.permissions = permissionFactory.fetch({ id: $stateParams.id);...

I don't think I can use this pattern simply because I am looping over the list.

Any help or guidence would be appreciated!

Upvotes: 4

Views: 117

Answers (1)

Avraam Mavridis
Avraam Mavridis

Reputation: 8920

ArrayOFPromises = [];

for (var i = 0, ii = $scope.Model.permissions.length; i < ii; i++) {
    //if id === 0, it is a new record
    if ($scope.Model.permissions[i].New === true && $scope.Model.permissions[i].Deleted === false) {
        ArrayOFPromises.push(angularService.update($scope.Model.permissions[i]));
    }
}

And then

$q.all(ArrayOFPromises).then(function () {
    //dosomething
});

Upvotes: 4

Related Questions