Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution.
After reading Mozilla's documentation on closures in loops, I decided to create inner closures.
When running this code snippet with IDs [1,2,3]
, the following output is expected:
makeRequestRecovery 1
makeRequestRecovery 2
makeRequestRecovery 3
failure
recover id 1
failure
recover id 1
failure
recover id 1
Here is the relevant code snippet:
var recoverRequest = function(entry) {
console.log('recover id', entry.data.id);
$scope.storage.entries.push(entry);
};
var makeRequestRecovery = function(entry) {
console.log('makeRequestRecovery', entry.data.id);
return function() {
recoverRequest(entry);
}
};
$scope.syncEntries = function() {
var initialLength = $scope.storage.entries.length;
var requestCount = 0;
while ($scope.storage.entries.length > 0) {
var entry = $scope.storage.entries.pop(0);
var recover = makeRequestRecovery(entry);
// restangular stuff...
// restangular HTTP REMOVE
entry.remove().then(function(data) {
console.log('success!', data);
}, function(data) {
console.log('failure', data);
recover();
});
requestCount++;
if (requestCount > 2 * initialLength) {
// too many requests failed
break;
}
}
}
I am now considering what changes need to be made in order to ensure that recover()
is executed with the correct value. Any suggestions?