[英]Calling a closure inside a promise callback
I'm implementing queue system for a webapp so that HTTP request that are failed are locally stored to be re-executed later on. 我正在为Web应用程序实现队列系统,以便将失败的HTTP请求本地存储以在以后重新执行。
I have read Mozilla's documentation about closure in loops and then created inner closures. 我已经阅读了Mozilla关于循环闭包的文档,然后创建了内部闭包。
If running this with ids [1,2,3]
, the output will be: 如果使用ids [1,2,3]
运行此命令,则输出为:
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? 我应该进行哪些更改,以便用正确的值执行recover()
?
I actually didn't use the closure properly. 我实际上没有正确使用闭包。 recover
needs to be passed as callback: recover
需要作为回调传递:
entry.remove().then(function(data) {
console.log('success!', data);
}, recover);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.