我写了一个带指数回退的实现,它不使用递归(这会创建嵌套的堆栈帧,是否正确?)它的实现方式有使用多个定时器,它总是为make_single_xhr_call创建所有堆栈帧(即使在成功之后,而不是在失败之后)。我不确定它是否值得(特别是如果平均情况是成功的话),但这是值得思考的。
我很担心调用之间的竞争条件,但是如果javascript是单线程的并且没有上下文切换(这会允许一个$ http.success被另一个中断并允许它执行两次)重新在这里,对不对?
此外,我很新的angularjs和现代的JavaScript,所以约定可能有点肮脏也。让我知道你的想法。
var app = angular.module("angular", []);
app.controller("Controller", ["$scope", "$http", "$timeout",
function($scope, $http, $timeout) {
/**
* Tries to make XmlHttpRequest call a few times with exponential backoff.
*
* The way this works is by setting a timeout for all the possible calls
* to make_single_xhr_call instantly (because $http is asynchronous) and
* make_single_xhr_call checks the global state ($scope.xhr_completed) to
* make sure another request was not already successful.
*
* With sleeptime = 0, inc = 1000, the calls will be performed around:
* t = 0
* t = 1000 (+1 second)
* t = 3000 (+2 seconds)
* t = 7000 (+4 seconds)
* t = 15000 (+8 seconds)
*/
$scope.repeatedly_xhr_call_until_success = function() {
var url = "/url/to/data";
$scope.xhr_completed = false
var sleeptime = 0;
var inc = 1000;
for (var i = 0, n = 5 ; i < n ; ++i) {
$timeout(function() {$scope.make_single_xhr_call(url);}, sleeptime);
sleeptime += inc;
inc = (inc << 1); // multiply inc by 2
}
};
/**
* Try to make a single XmlHttpRequest and do something with the data.
*/
$scope.make_single_xhr_call = function(url) {
console.log("Making XHR Request to " + url);
// avoid making the call if it has already been successful
if ($scope.xhr_completed) return;
$http.get(url)
.success(function(data, status, headers) {
// this would be later (after the server responded)-- maybe another
// one of the calls has already completed.
if ($scope.xhr_completed) return;
$scope.xhr_completed = true;
console.log("XHR was successful");
// do something with XHR data
})
.error(function(data, status, headers) {
console.log("XHR failed.");
});
};
}]);
是,重新连接重新在服务中,这样,在控制器中,您可以简单地获得已解析的数据。 – tymeJV
定义您的功能并将其命名。在拒绝中打电话给它。那简单! – Mohsen
试图在控制器中返回$ scope.getData(query),但不再发送承诺 – Angelin