简体   繁体   English

同时进行多个AJAX调用和连续进行它们之间有区别吗?

[英]Is there a difference between making multiple AJAX calls simultaneously and making them consecutively?

I am using jQuery, and jQuery Mobile to make a mobile app, if that matters that much. 我使用jQuery和jQuery Mobile制作移动应用程序,如果那很重要的话。

My question is, is it better practice to perform multiple AJAX calls one way or the other? 我的问题是,以一种方式或另一种方式执行多个AJAX调用是更好的做法吗?

For example, having a variable that counts all the ajax calls, and then if that variable maxes out, call the complete function such as: 例如,拥有一个对所有ajax调用进行计数的变量,然后,如果该变量用尽,则调用完整的函数,例如:

var count = 0
$.ajax({
    //stuff
}).done({
    count++;
    if(count == 5){
        complete();
    }
});
...

or is it better to run them in a chain like: 还是将它们按以下链式运行是更好的方法:

$.ajax({
    //stuff
}).done({
    $.ajax({
        //stuff
    }).done({
        $.ajax({
            //stuff
        }).done({
            //do complete stuff
        });
    });
});

The application is that multiple API calls need to be made to gather all the information necessary and then manipulate something afterwards. 应用程序是需要进行多个API调用以收集所有必要的信息,然后再进行操作。 Is there a difference performance wise and is there a "best practice"? 在性能上有区别吗?是否有“最佳实践”?

Do what's best for your application. 做最适合您的应用程序的事情。 If you have multiple independent sets of data to fetch and you don't rely on data from one set before fetching the other, then by all means request all of them simultaneously. 如果要提取多个独立的数据集,并且在获取另一个数据集之前不依赖其中的数据,则一定要同时请求所有数据。 Let the browser worry about throttling them. 让浏览器担心限制它们。

Also, don't use your counting method to make sure they all finished. 另外,请勿使用计数方法来确保它们全部完成。 jQuery returns a handy Deferred object with AJAX requests. jQuery返回带有AJAX请求的便捷Deferred对象。 Untested and simplified, but this should get you started: 未经测试和简化,但这应该可以帮助您入门:

$.when (
  $.ajax('/data1'),
  $.ajax('/data2'),
  $.ajax('/data3')
).done(function (data1, data2, data3) {
  console.log(arguments);
});

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM