Ph33ly
Ph33ly

Reputation: 693

Controlling AJAX requests

Is there anyway to halt additional AJAX requests and fire them one at a time? I have a printing application so I need to process each request before moving on to the next. In my code I have a loop iterating on average of about 15 times that will make the AJAX call for each iteration and process that response $.when() ready. The problem is that each response gets processed as they are returned, not when the previous one has finished. I'm really trying to avoid making my calls synchronous, but is there anyway to process these responses one at a time?

Upvotes: 0

Views: 110

Answers (1)

Kevin B
Kevin B

Reputation: 95022

Yes, store the promise in the original array, then loop over the original array again to pass to $.when. The callback will have arguments in order.

var myData = [
  {
    name: 'apple',
    color: 'red'
  },
  {
    name: 'orange',
    color: 'orange'
  }
];

myData.forEach(function (obj) {
  obj.promise = $.get('/object-info', obj);
});

$.when.apply($, myData.map(function (obj) {
  return obj.promise;
})).then(function () {
  var args = Array.prototype.slice.call(arguments);
  args.forEach(function (result) {
    console.log(result); // results in order
  })
});

// *** MOCK

$.get = function (url, data) {
    var defer = $.Deferred()
    setTimeout(function () {
        defer.resolve(data.color);
    }, 1500);
    return defer.promise();
};

// *** END MOCK

var myData = [
  {
    name: 'apple',
    color: 'red'
  },
  {
    name: 'orange',
    color: 'orange'
  }
];

myData.forEach(function (obj) {
  obj.promise = $.get('/object-info', obj);
});

$.when.apply($, myData.map(function (obj) {
  return obj.promise;
})).then(function () {
  var args = Array.prototype.slice.call(arguments);
  args.forEach(function (result) {
    console.log(result); // results in order
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions