简体   繁体   中英

How can I update data in a for loop when my data is returned with a defer after the loop completes

I have two arrays:

$scope.grid.data and $scope.grid.backup

I use the following script to compare the data in each one element at a time:

for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
    if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
        var rowData = $scope.grid.data[i]
        var idColumn = $scope.entityType.toLowerCase() + 'Id';
        var entityId = rowData[idColumn];
        entityService.putEntity($scope.entityType, entityId, $scope.grid.data[i])
            .then(function (result) {
                angular.copy(result, $scope.grid.data[i]);
                angular.copy(result, $scope.grid.backup[i]);
            }, function (result) {
                alert("Error: " + result);
            })
    }
}

and the following to update the database:

putEntity: function (entityType, entityId, entity) {
    var deferred = $q.defer();
    EntityResource.putEntity({ entityType: entityType, entityId: entityId }, entity,
       function (resp) {
           deferred.resolve(resp);
       }, function (resp) {
        deferred.reject('Error updating');
    });
    return deferred.promise;
}

This script correctly notices the changes and updates the database.

However there is a problem when the putEntity returns with a result and it then tries to copy the result into $scope.grid.data[i] and $scope.grid.backup[i]

This happens later and when it tries to do this it always tries to put it into element 11.

Does anyone have any ideas how I can ensure the returned data from putEntity is copied back into the correct element of the grid.data and grid.backup arrays?

You need to create a closure over i. What you can do is create a function

var updateGridData=function(entityType, entityId, gridDataToUpdate, gridIndex) 
entityService.putEntity(entityType, entityId,gridDataToUpdate)
            .then(function (result) {
                angular.copy(result, $scope.grid.data[gridIndex]);
                angular.copy(result, $scope.grid.backup[gridIndex]);
            }, function (result) {
                alert("Error: " + result);
            })

}

So your main method becomes

for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
    if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
        var rowData = $scope.grid.data[i]
        var idColumn = $scope.entityType.toLowerCase() + 'Id';
        var entityId = rowData[idColumn];
        updateGridData($scope.entityType, entityId, $scope.grid.data[i],i);
    }
}

You can get some more idea from this question JavaScript closure inside loops – simple practical example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM