开发者

AJAX asynchronous response callbacks

开发者 https://www.devze.com 2023-04-08 20:15 出处:网络
I have been working with AJAX for a while now, but in limited and simple ways. I use JQuery Currently I am debugging a web application. The client side code uses JavaScript and JQuery. I noticed that

I have been working with AJAX for a while now, but in limited and simple ways. I use JQuery

Currently I am debugging a web application. The client side code uses JavaScript and JQuery. I noticed that in this application it is possible to have multiple AJAX requests sent out at the same time (one right after the other). My concern is that because AJAX is asynchronous that the AJAX request might not be completed in the correct order. I was wondering if the proper AJAX callbacks will be executed regardless of witch response is returns first or the call back functions are executed in FIFO manner

Let me elaborate

I have 2 AJAX requests A and B. Both A and B have there own call back functions. The app first makes request A then immediately afterward makes request B. Now the App expects A to return first. Now my question is what if B returns first. Which Call back will be executed?

I did some re开发者_开发知识库search and could not find any info on this issue. So I assumed that the browser would coordinate the callbacks. To make sure I wrote a little test. My test showed that regardless of which response returns first the first requests call back is always used first.

My question is what is the behavior? Also what techniques or methods are used to avoid such a case.


Look at the jQuery promise/deferred objects, they allow you to control this exact behavior.

$.when( $.ajax("test.aspx") ).then( $.ajax("test2.aspx") );

http://api.jquery.com/category/deferred-object/


As you described the flow - if the request B returns first, then its callback will be called first.

You can always call the second ajax request when the first one suceed, for example:

function callbackA() { return true; }
function callbackB() { return true; }

$.ajax({url: '/my/url', data: {mydata: mydata}, success: function(data) {
      callbackA(data);
      $.ajax({url: '/my/url2', data: {mydata2: mydata2}, success: function(data) {}
          callbackB(data);
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号