如何处理大量的AJAX请求(> 1000)
我的应用正在从客户端的Google联系人API提取用户的所有Google联系人.这通常会导致1-2000个不同的JSON对象.接收到这些内容后,我的应用程序将对其进行遍历,重新格式化每个联系人对象,然后尝试通过POST请求将重新格式化后的联系人对象保存到我的数据库中.这样做的结果是在客户端触发了大量(1-2000)AJAX调用,但是在5-10个调用之后它们停止了.处理所有这些AJAX请求或一次保存如此大量数据的最佳方法是什么?
My app is fetching all of a User's Google Contacts from the Google Contacts API on the client side. This usually results in between 1 - 2000 different JSON objects. When those are received, my app iterates through them, reformats each Contact Object, and then attempts to save the reformatted Contact Object to my database via a POST request. The result of this is a large number ( 1 - 2000 ) of AJAX calls firing on the Client Side, but they stall out after 5-10 of them. What is the best way to handle all of these AJAX requests, or saving such a large amount of data all at once?
这是我当前代码的摘要版本:
Here is a summarized version of my current code:
// gContacts.length = 722
$(gContacts).each(function(index, contact) {
// Reformat each contact object to fit into my database
var newContact = {}
newContact.title = // String
newContact.emails = // Object featuring different emails
newContact.phone_numbers = // Object featuring different phonenumbers
// Save to Database via Backbone
var newContact = new App.Collections.Contacts()
newContact.create({
title : newContact.title,
emails : newContact.emails,
phone_numbers : newContact.phone_numbers
}, {
success: function (response) {
},
error: function (model, xhr) {
var errors = $.parseJSON(xhr.responseText).errors
console.log(errors)
}
}) // End .save
}); // End of .each()
我将执行服务器端操作,该操作将获取联系人对象的整个列表.然后在客户端上,只需格式化它们并将它们全部添加到数组中,一旦完成,就发送该数组.您这样做的方式会导致很多不必要的网络开销.
I would make a server-side action that takes a whole list of contact objects. Then on the client side, just format them and add them all to an array, and once that's done send the array. The way you're doing it incurs a lot of unnecessary network overhead.