简体   繁体   中英

Ajax call inside a loop

I have a loop in my jQuery code. Inside the loop there is an AJAX call. Since for each loop an AJAX call to the server is fired, does it mean a new thread is created for each call at the server side? Do all calls get a new thread? This is my jQuery code for your reference:

function Run() {
  var i = 0;
  var r = '${result}'
  var par = '${paramy}'
  var str = r.replace(/\r?\n|\r/g, " ");
  var resjson = JSON.parse(str);
  var parjson = JSON.parse(par);

  //loop to send ajax req multiple times. 
  for (var i = 0; i < resjson.length; i++) {
    var k = i + 1;
    var m = encodeURIComponent(JSON.stringify(resjson[i]));
    var py = encodeURIComponent(JSON.stringify(parjson));
    var pass = '';

    $.ajax({
      type: 'post', // it's easier to read GET request parameters
      url: 'servlet1',
      async: true,
      data: { 
        r: m,
        p:py
      },
      success: function(data) {
        console.log("pass"`enter code here`)
      },
      error: function(data) {
        console.log("fail"); 
      }
    });
  }
}

Since for each loop an AJAX call to the server is fired, does it mean a new thread is created for each call at the server side?

That depends entirely on the infrastructure being used on the server side. Few servers would create a brand-new thread for each request but many would assign a thread from a pool to each request, and return that thread to the pool when the request is serviced.

Each AJAX call creates a new XHR, no matters if it is called in a loop or not. If "async: false" that means jquery will wait till the request is completed/failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM