如何处理大量AJAX请求(> 1000)

ac3*_*360 1 javascript ajax jquery express backbone.js

我的应用程序从客户端的Google Contacts API获取用户的所有Google通讯录.这通常会导致1到2000个不同的JSON对象.当收到这些文件时,我的应用程序会遍历它们,重新格式化每个联系人对象,然后尝试通过POST请求将重新格式化的联系人对象保存到我的数据库.结果是在客户端触发了大量(1 - 2000)的AJAX调用,但是在5-10个调用之后它们就停止了.处理所有这些AJAX请求或一次性保存如此大量数据的最佳方法是什么?

这是我当前代码的摘要版本:

// 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()
Run Code Online (Sandbox Code Playgroud)

小智 7

我会做一个服务器端操作,它需要一个联系对象的完整列表.然后在客户端,只需格式化它们并将它们全部添加到数组中,一旦完成,就发送数组.你这样做的方式会带来很多不必要的网络开销.