是事件处理程序保证完成AJAX回调被调用之前? [英] Are event handlers guaranteed to complete before AJAX callbacks are invoked?

查看:138
本文介绍了是事件处理程序保证完成AJAX回调被调用之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个事件处理这提出了两个AJAX调用到服务器:

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

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

我认识到,在该回调调用的顺序是不确定的,因为它取决于多久每个请求需要等。

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

但这里是我的问题:这是保证,我会任的回调函数之前达到我的事件处理结束时调用的?我读过的所有的JavaScript的网页在一个线程中执行,所以我觉得这意味着,我的点击事件处理程序,保证在任何回调来完成即可调用。

But here's my question: is it guaranteed that I'll reach the end of my event handler before either of the callback functions are invoked? I've read that all Javascript for a page executes in a single thread, so I think that implies that my click event handler is guaranteed to complete before any of the callbacks can be invoked.

这是正确的?或者是有可能的第一个请求可能是完整的,第一次回调执行之前,我们甚至到达我们的事件处理程序的终结?

Is this correct? Or is it possible that the first request might be complete AND the first callback executed before we even get to the end of our event handler?

推荐答案

是的,这是保证你是对的 - 也只是一个单独的线程(忽略的网络工作者 S为时刻)。当一块的JavaScript code执行时的(占用的执行线程)和一个AJAX回调到达(或任何其它的GUI事件,超时,等等)它被排队并等待执行线程是免费的(当前片$的c $ C完成)。

Yes, this is guaranteed and you are right - there is just a single thread (ignoring web-workers for the moment). When a piece of JavaScript code executes (occupies the execution thread) and an AJAX callback arrives (or any other GUI event, timeout, etc.) it is queued and waits until the execution thread is free (current piece of code finishes).

JavaScript引擎将不会中断运行code来处理传入的事件 - 事件总是会轻轻地排队等待。这就是为什么GUI出现时,CPU密集型code正在执行被冻结的原因 - 没有任何事件的处理。另外这也就是为什么同步的AJAX请求是坏的。

JavaScript engine will never interrupt running code to handle incoming event - events will always gently wait in a queue. This is the reason why the GUI appears to be freezing when CPU-intensive code is executing - no events are handled. Also this is why synchronous AJAX requests are bad.

  • JavaScript equivalent of SwingUtilities.invokeLater()
  • "atomic" operation desturbed by asynchronous ajax callbacks
  • Are there any atomic javascript operations to deal with Ajax's asynchronous nature?
  • how is async programming (promises) implemented in javascript? isn't javascript a ui-threaded environment?

这篇关于是事件处理程序保证完成AJAX回调被调用之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆