如何同步依赖于多个ajax请求响应的javascript代码?
通常,我会使用传递给“jQuery.getJSON”函数的回调函数在服务器响应后执行某些操作。在本例中,我在某些输入元素上应用了事件处理程序,但这些处理程序应该仅在多个 ajax 请求成功后执行。基本上我需要暂停事件处理程序的执行,直到我期望的一些数据可用。
在多线程语言中,我会使用互斥体/信号量来做到这一点,但由于 javascript 是单线程的,我想知道这样的事情是否可能。
Normally, I would use a callback function passed to the 'jQuery.getJSON' function to do something after the server responds. In this case, I have applied event handlers on some input elements, but these handlers should only execute after the success of multiple ajax requests. Basically I need to pause the execution of the event handler until some data I expect is avaliable.
In multi-threaded languages I would do it using mutexes/semaphores, but since javascript is single threaded I wonder if something like this is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行此操作的一种手动方法是将 AJAX 调用放入数组中排队,然后计算收到的响应数量,并等待该计数与原始队列的大小匹配(或者,将调用弹出)响应完成时的队列,并且当队列大小为 0 时,您知道您已经拥有了所有内容)。
您必须检查是否准备好继续进行 setTimeout 调用。
或者,您可以查看 jQuery 1.5+ 中的延迟支持
编辑:手动方法的快速而肮脏的示例:
One manual way to do this is to queue up your AJAX calls in an array, and then count the number of responses you've received and wait until that count matches the size of your original queue (or, alternatively, pop the call out of the queue when the response is done, and you know you have everything when the queue is of 0 size).
You would have to check whether or not you are ready to proceed with a setTimeout call.
Alternatively, you may check out Deferred support in jQuery 1.5+
EDIT: A quick and dirty example of a manual approach:
javascript 是基于事件的,因此一种方法是每次协调的 xhr 获得其响应时抛出一个事件。事件处理程序跟踪响应,并且仅在所有响应都返回时才继续。
或者,您可以在没有事件的情况下执行相同的操作,只需直接调用方法并协调其中的响应......
javascript is event-based, so one approach is to throw an event each time a coordinated xhr gets its response. The event handler tracks the responses and only proceeds when all are returned.
Or you can do the same thing without events, just by calling a method directly and coordinating the responses in there....
我可以给你一个肮脏的解决方案。创建所有查询返回后要执行的函数。创建另一个函数来执行调度。就像信号量/互斥体一样,创建一个“同步”变量。增加每个调用的变量。然后,在调度函数中,递减变量,如果为零,则执行所需的函数。将调度函数应用为 ajax 返回的事件处理程序(如果您已有不想暂停的处理程序,请将其放在每个现有处理程序的末尾)。
然后,想一个更优雅的解决方案。
I can give you a dirty solution. Create the function you want to execute once all queries return. Create another function to do the dispatch. Just like a semaphore/mutex, make a "synchronization" variable. Increment the variable for each of the calls. Then, in the dispatch function, decrement the variable and if zero, execute the function you want. Apply the dispatch function as the event handler for the ajax return (if you already have handlers that you don't want to pause, put it at the end of each existing handler).
Then, think of a more elegant solution.