多次ajax调用成功后触发事件
我想知道在几次(无序)ajax 调用完成后触发事件的最佳方法是什么。
为了让它更清楚一点,我想调用一个方法 doSomethingGreat() ,它会触发多个 ajax 调用,这些调用的成功顺序是不必要的。我只想在所有这些调用成功时触发一个事件“SomethingGreatFinished”。我也不想链接这些调用,因为这会缺乏性能并且完全违背异步编程的思想。
我想知道是否 a.) 有一个通用的模式,b.) 这可以通过 JavaScript 的响应式扩展 (RxJs) 或 c.) 具有本机 jquery 功能来完成。
任何帮助表示赞赏!
I wonder which is the best approach to trigger an event after several (unordered) ajax calls finished.
To make it a bit clearer, I would like to call a Method doSomethingGreat() which triggers several ajax calls, the order in which those succeed ins unnecessary. I just want to trigger an event 'SomethingGreatFinished' when all of those calls succeeded. I also don't want to chain these calls, because that would be lacking performance and would be totally against the idea of asynchronous programming.
I wonder if a.) there is a common pattern for that, b.) this can be done with the Reactive Extensions for JavaScript (RxJs) or c.) with native jquery features.
Any help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
RxJS 将允许您使用 ForkJoin 运算符来执行此操作,该运算符采用带有值的 N 个可观察量,并创建一个可观察量,当所有 N 个可观察量完成时,该可观察量将使用数组触发。
请参阅 Matthew Podwysocki 关于此运算符的博客文章:http://codebetter.com/blogs/matthew.podwysocki/archive/2010/04/23/introduction-to-the-reactive-extensions-for -javascript-going-parallel-with-forkjoin.aspx
RxJS will allow you to do this using the ForkJoin operator, this operator takes N observables with a value and creates one observable that fires with an array when all N observables complete.
See Matthew Podwysocki's blog post about this operator: http://codebetter.com/blogs/matthew.podwysocki/archive/2010/04/23/introduction-to-the-reactive-extensions-for-javascript-going-parallel-with-forkjoin.aspx
您应该查看 .ajaxStop()。
但是,该回调将在每个完成的 ajax 请求上触发。因此,为了知道您的最后请求何时完成,您需要调用 .ajaxStart () 也是如此,或者您需要为您触发的每个请求迭代一个
全局变量
,并在.ajaxStop()
上递减
它。如果该变量达到零
,则您的所有请求均已完成。You should have a look at .ajaxStop().
However, that
callback
will fire on every single ajax request that completes. So in order to know when your last request completes, you need either to invoke .ajaxStart() aswell, or you need to iterate aglobal variable
for each request you fire anddecrement
it on.ajaxStop()
. If that variable reacheszero
, all your request have completed.如果您知道进行了多少次调用,则将一个变量设置为该数字,并在每次发生 AJAX 完成事件时递减该数字。当变量达到零时,“SomethingGreat”就发生了。
If you know how many calls are being made, then set a variable to that number, and decrement it each time an AJAX completion event occurs. When the variable reaches zero, 'SomethingGreat' has happened.