随时间延迟的角度多HTTP循环请求



我的ID数组包含50 ID。

var ids = [
    '3407197',
    '0632706',
    '18275',
    ...,
    ...
]

我想通过循环发送Angular HTTP获取请求。每次迭代将延迟10秒延迟。当所有请求完成后,它将通知请求已完成。

我尝试过此代码,但它立即执行不延迟。

function collector(i){
    setTimeout(function() {
        return $http.get('http://example.com/' + ids[i])
          .success(function(data) {
          })
          .error(function(err) {
          })
    },10000);
 }

 $scope.getAllData = function() {
    var promises = [];
    for (var i = 0; i < ids.length; i++) {
      promises.push(collector(i));
    }
    return $q.all(promises);
  }
  $scope.getAllData ().then(function(data) {
    $scope.debug = 'done';
  });

尝试使用$timeout

function getRequest(id) {
    return $http.get('http://example.com/' + id)
        .success(function (data) {})
        .error(function (err) {});   
}
var promise = $timeout();
ids.forEach(function(id) {
     promise = promise.then(function() {
         getRequest(id);
         return $timeout(10000);
     });
});
// not sure if this works
promise.then(function() {
    $scope.debug = 'done';
});

最新更新