3

I'm new to JS, so please forgive me if I have any mistakes.

I have a "unknown" number of URLs in a array, and I have to get them using Ajax, but not asynchronously. I want them to be retrieved one after another, but my current code fires everything at the same time.

Any assistance is appreciated - my current code is something like below:

urls = ["http://www.google.com/", "http://www.yahoo.com", "http://www.bing.com"] // the number of urls in this array changes

var gets = []

$.each(urls, function(index, url) {
  gets.push($.ajax({
    url: url
  }));
});
  • Something like [this](http://stackoverflow.com/questions/9235237/jquery-how-to-use-multiple-ajax-calls-one-after-the-end-of-the-other) – machineaddict Jul 04 '14 at 08:30

4 Answers4

1

Because ajax returns a promise, you can chain obtaining the result with the next invocation.

var urls = ["http://www.google.com/", "http://www.yahoo.com", "http://www.bing.com"]

(function(arrayurls, index) {
  if(index >= arrayurls.length) return;
  var url = arrayurls[index];
  var thisfunction = arguments.callee;
  $.ajax({ url: url }).done(function(result) {
     //Do something with the result.
     thisfunction(arrayurls, index + 1) // Reinvoke the function over different arguments.
  });
})(urls, 0);

Named variant to get rid of arguments.callee:

var handle = function(arrayurls: string[], index: number) {
  if(index >= arrayurls.length) return;
  var url = arrayurls[index];
  $.ajax({ url: url }).done(function(result) {
     //Do something with the result.
     handle(arrayurls, index + 1) // Reinvoke the request over the next URL arguments.
  });
};
handle(urls, 0);

If the number of urls is going to change over time while this invocation is made, you can always copy the url array with urls.slice(0);

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101
0

You can pass async=false parameter with your ajax call. This makes the next ajax calls to wait until the previous call has completed. Something like below code should work:

$.ajax({
        url : url,
        type : "get",
        async : false,
        success : function(data) {
                your logic
        }
    });
Ankit Jaiswal
  • 22,859
  • 5
  • 41
  • 64
0

Have a look at : https://stackoverflow.com/a/4785886/2561834. You need an class/function to handle your stack of requests.

Community
  • 1
  • 1
Tanatos
  • 1,857
  • 1
  • 13
  • 12
-1

You can set async: false. Docs.

Shubham
  • 21,300
  • 18
  • 66
  • 89