I'm implementing queue system for a webapp so that HTTP request that are failed are locally stored to be re-executed later on.
I have read Mozilla's documentation about closure in loops and then created inner closures.
If running this with ids [1,2,3]
, the output will be:
makeRequestRecovery 1
makeRequestRecovery 2
makeRequestRecovery 3
failure
recover id 1
failure
recover id 1
failure
recover id 1
code:
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;
}
}
}
What changes should I make so recover()
is executed with the right value?
I actually didn't use the closure properly. recover
needs to be passed as callback:
entry.remove().then(function(data) {
console.log('success!', data);
}, recover);
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.