我正在为webapp实现队列系统,以便在本地存储失败的HTTP请求,以便稍后重新执行。
我已阅读Mozilla关于closure in loops的文档,然后创建了内部闭包。
如果使用ids [1,2,3]
运行此选项,则输出将为:
makeRequestRecovery 1
makeRequestRecovery 2
makeRequestRecovery 3
failure
recover id 1
failure
recover id 1
failure
recover id 1
代码:
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;
}
}
}
我应该做出哪些更改,以便使用正确的值执行recover()
?
答案 0 :(得分:0)
我实际上没有正确使用关闭。
recover
需要作为回调传递:
entry.remove().then(function(data) {
console.log('success!', data);
}, recover);