如何根据以前的ajax响应在循环中触发ajax请求

时间:2015-12-24 08:50:26

标签: angularjs angular-promise

我有每个地址需要更新数量属性的选定送货地址列表,如果之前的更新失败,则根据先前的更新响应需要中止循环。

这是我目前的代码段。

    $scope.applyQty = (qty) ->
      collections = $filter('filter')($scope.address, {checked: true}, true) #return array of objects
      x = true
      angular.forEach(collections, (address) ->    
        if x
          address.quantity = qty    
          promise = $scope.saveMethod(address)
          promise.then ( (respone) ->
            #dosomething     
          ), (error) ->
            x = false #stop next address
          )
...
$scope.saveMethod = (address) ->
  deferred = $q.defer()
  #some logic
  ..
  #ajax call to update quantity
  address.save().then ((response) ->
    deferred.resolve(response)
  ), (error) ->
    deferred.reject(error)
    address.quantity = 0

  return deferred.promise;

在applyQty方法中循环调用saveMethod的选定送货地址。如果服务器端的一个地址无法更新,请停止循环。

1 个答案:

答案 0 :(得分:0)

如果以适当的方式使用$ q服务,因为我们将承诺返回到下一次执行,我使用

模拟此代码
var chaingAjax = function(item) {
  // smiulte ajax request
  var defer = $q.defer();

  $timeout(function() {
    // assume error happen at item 4 execution will end and return error message
    if (item != 4) {
      defer.resolve(item);
      console.log('posted ' + item)
    } else {
      console.log('error 4')
      return defer.reject({
        error: 'bad call ajax stoped at ' + item
      });
    }
  }, 500);

  return defer.promise;
}

var executeList = function(list) {
  console.log(list)
  var item = list.pop()
  var promise = chaingAjax(item).then(function(saved) {
    console.log(saved)
    executeList(list)
  }, function(error) {
    console.log(error)
  });
  return promise
}


executeList([1, 2, 3, 4, 5, 6])
  .then(function() {
    $scope.value = "all done";
  }, function(e) {
    $scope.value = e.error;
  });

你可以使用$ http.post()或任何返回promise的函数

var exeuteMyAjaxCall =  function (list){
    var item = list.pop();
    var promise = $http.post('url', {data:item})
                  .then(function(success){
                       exeuteMyAjaxCall(list);
                   },function(error){ 
                   })

    return promise;
}


exeuteMyAjaxCall (arrayOfData)
  .then(function() {
    $scope.value = "all done";
  }, function(e) {
    $scope.value = e.error;
  });