3

我正在尝试使用 foreach 中的顺序 http 请求更新进度条,这可行,但是在完成时它不是同步的,进度条正在通过 http 调用同步,我做错了什么?

angular.forEach(queue, function (item) {
    if (item.uid) {
        d.item = item;
        $http({
            url: BASE_URL + 'upp', 
            method: 'post',
            data: d                  
        }).then(function(res){
            x++;
            update_progress((x/queue_count)*100);
        });
    }
});

我想在 http 返回完成(200 OK)时调用 update_progress 函数,因此进度条正确显示实际进度。谢谢!

编辑

在调用 *update_progress* 函数之前,我尝试检查响应状态,但它仍然无法按预期工作。我不知道在请求完成之前发送了 200 :| 按逻辑,res obj不应该是http请求的响应吗?我的意思是,如果它是 200 而不是错误代码,那不应该意味着请求已完成?

angular.forEach(queue, function (item) {
if (item.uid) {
    d.item = item;
    $http({
        url: BASE_URL + 'upp', 
        method: 'post',
        data: d                  
    }).then(function(res){
        if(res.status == 200) {
          x++;
          update_progress((x/queue_count)*100);
        }
    });
}

阅读更多关于 promises atm 的内容,看看我是否可以按照@josh-strange 的说法让它工作

编辑 2

所以 promises 是这样做的方法,所有请求都是按顺序发送的,所以进度条按预期工作,这里是代码:

var promise = $q.all({}); 
// Had to init $q.all with an empty obj, 'cause null was trowing errors

angular.forEach(queue, function(item){
  if (item.uid) {        
    promise = promise.then(function(){
      d.item = item;
      return $http({
        url: BASE_URL + 'upp', 
        method: 'post',
        data: d 
      }).then(function(res){
        x++;
        update_progress((x/queue_count)*100);
      });
    });
  }
});

promise.then(function(){
  end_js_update();
});

谢谢@josh-strange

4

2 回答 2

13

这是顺序 http 请求的工作示例的工作Plunker。您显然可以将其很好地打包到服务中,但出于您的目的,我只是在控制器中放置了一个简单的示例。

这是代码的“肉”:

var app = angular.module('testApp',[]);

app.controller('myController', function($scope, $http, $q){

  $scope.responses = [];
  $scope.doneLoading = false;
  var urls = [
    'http://httpbin.org/ip',
    'http://httpbin.org/user-agent',
    'http://httpbin.org/headers'
  ];

  var promise = $q.all(null);

  angular.forEach(urls, function(url){
    promise = promise.then(function(){
      return $http({
        method: 'GET', 
        url:url 
      }).then(function(res){
        $scope.responses.push(res.data);
      });
    });
  });

  promise.then(function(){
    //This is run after all of your HTTP requests are done
    $scope.doneLoading = true;
  })

});

编辑:正如 Mike P 所说:这是链接承诺的示例,请参阅$q 文档

于 2013-09-26T20:57:50.687 回答
0

你可以试试这样的。只是等到前一个请求完成后再发送下一个请求?

var sendRequest = function(index) {
  if (queue[index].uid) {
    d.item = queue[index];
    $http({
      url: BASE_URL + 'upp', 
      method: 'post',
      data: d                  
    }).then(function(res){
      if (index != queue.length - 1) {
        x++;
        update_progress((x / queue_count) * 100);
        sendRequest(++index);
      }
    });
  }
}
于 2013-09-26T20:34:08.240 回答