Are event handlers guaranteed to complete before AJAX callbacks are invoked?

后端 未结 4 711
面向向阳花
面向向阳花 2020-12-31 11:21

Suppose I have a event handler which makes two AJAX calls to the server:

$(\"#foo\").click(function(){ 
    $.get(\"bar\", function(){ alert(\"Hello\"); });
         


        
4条回答
  •  囚心锁ツ
    2020-12-31 12:13

    I realize that the order in which the callbacks are invoked is nondeterministic, since it depends on how long each request takes, etc.

    In the way you have written it yes.. but there are ways to organize and control this.. namely deffereds and promises.

    Here is a good overview: http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/

    Proper use of them will ensure that you won't run into whatever problem you seem to be trying to avoid.

    ** As @Juan has pointed out, this isn't the black and white answer for the question you asked. I'm just trying to point you in different directions or ways to look at the same problem so you can define your expected behavior more explicitly.

提交回复
热议问题