多个连续ajax请求的jquery模式
我有一个带有数组的 for every 循环,对于数组中的每个元素,我需要从服务器检索数据,因此我将为每个元素发出 ajax 请求并将结果存储在另一个数组中,我需要知道最后一个元素何时数组已经过处理,所以我可以显示数据,是否有一种模式,或者我怎样才能做到这一点而不使事情变得过于复杂,我认为这就是我正在做的事情
I have a for each loop with an array, for each element in the array I need to retrieve data from the server so I will make an ajax request per element and store the result in another array, I need to know when the last element in the array has been processed so I can display the data, is there a pattern or how could I do this without over complicating things which I think is what I'm doing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后,在 XHR 的回调中,
或者,您声明要将这些内容添加到新数组中。假设完成后数组的长度相等,您可以将回调中的检查更改为
(startArray.length == newArray.length)
。另外,请记住,如果您在循环中制作 XHR(假设异步),它们将几乎同时尝试请求(我认为),这可能是性能问题。考虑编写一个在每个单独请求的回调中再次调用的函数,以便一次生成一个 XHR。递增计数器,以便您可以在每次调用中为下一个数组元素添加下标。
Then, in the callbacks of your XHR,
Alternatively, you state that you are adding the things to a new array. Assuming that when finished the arrays will be of equal length, you can change the check in the callback to
(startArray.length == newArray.length)
.Also, keep in mind if you are making XHR (assuming asynchronous) in a loop, they will all be trying to request at roughly the same time (I think), which may be an issue with performance. Consider writing a function which is called again on each individual request's callback, so the XHRs are made one at a time. Increment a counter so you can subscript the next array element in each call.
具有“并行”模式的连续传递库将很好地抽象这一点。我正在使用 JooseX-CPS,另请参阅其 教程。
A continuation passing library that has a "parallel" mode will abstract this nicely. I'm using JooseX-CPS, also see its tutorial.
对于每一次成功,计算成功的结果,然后触发一个事件。
例如:
然后监听事件
这可以让您在循环之外的某个地方测试完成情况。
For each on success you hit, count up the successful results and then trigger an event.
For example:
and then listen for your event
This lets you test the completion somewhere outside of the loop.