n4gys4nyi
n4gys4nyi

Reputation: 933

jquery ajax requests with when is not executing properly

I want to start 8 ajax get requests N number of times, my code is like:

var me = this;
urls.forEach(function(requests){
  $.when(requests.map(function(request){
    return $.ajax(request)
  })).done(function(data){
    me.result.push(data);
    //data is an array of 8 where every object is coming from those requests
  })
})

If I put a breakpoint inside the done functions callback every object is an empty ajax object, but if I wait for a little after the success function was called N times and I check this.result the data is correct there. Why is 'done' success called too early?

Upvotes: 2

Views: 45

Answers (1)

Edwin Krause
Edwin Krause

Reputation: 1806

This is just an untested idea... Shouldn't it work a bit simpler...

var result = [];
var urls = ["http://url1.com","http://url2.com","http://url3.com"];

urls.forEach(function(str_url){
  $.ajax({
    url: str_url
  }).done(function(data){
    result.push(data);
    //data is an array of 8 where every object is coming from those requests
  });
});

Upvotes: 1

Related Questions