简体   繁体   中英

Unable to retrieve data from parallel ajax calls

I have a function below (searchTerm) which is supposed to fetch data from two URL's simultaneously and display the result after both the calls are completed.

This is working fine when I call with only one parameter in .when (say $.ajax(options1) ),

but as I need the output from both in parallel, I am calling both URL's and recording responses data1 and data2 in .then function, but now it is not getting called after the ajax calls are completed.

Can anyone tell if I am correct in this approach? If so, then why is the callback not getting executed?

var searchTerm = function() {

  var $a = $(this);
  var term = $("#searchbox").val();

  var options1 = {
      url: "someurl1",
      contentType: "application/json",
      data: JSON.stringify({
          searchString: term
      }),
      type: "post",
      dataType: "html"
  };

  var options2 = {
      url: "someurl2",
      contentType: "application/json",
      data: JSON.stringify({
          searchString: term
      }),
      type: "post",
      dataType: "html"
  };

  $.when($.ajax(options1), $.ajax(options2)).then(function(data1, data2) {
      alert("callbacks finished");
  });

Info1:
It seems any ajax call I specify as first argument is failing with 500 server error. I tried swapping options1 and options2, and now the call with options2 fails.

Info2:
The url that I have mentioned as part of options1 and options2 point to action methods in the same controller and they both return awaitable Task of (ActionResult) object. Can this be the problem here? Are the calls somehow blocking/interrupting each other over async requests?

Info 3:
Trying to provide more details to work with. The definition of the action methods are like this -

public async Task<ActionResult> someurl1(.....){
...
...
return await View(...);
}

Finally, I found the answer after debugging through all the subsequent calls. I was calling a common function from both action methods which uses a global variable to make external URL calls. Simply used the below locking mechanism to make my critical section thread-safe.

public static object Lock = new object();

lock (Lock) // added for thread safety purpose
{
    response_task = CallExtern(...)
}

Try adding the option

async: false

to the ajax objects.

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