繁体   English   中英

jQuery 异步 ajax 调用

[英]jQuery async ajax calls

我有以下代码,其中包含一个列表,并且对于此列表中的每个元素,执行 ajax 调用。

util.testMethod = function(list) {

            var map = new Map();

            list.forEach(function(data) {
                $.ajax({
                    url: 'https://......',
                    type: 'GET',
                    data: // data needed here
                    success: function(data) {
                        // do something
                    },
                    error: function(jqxhr, settings, exception) {
                        // dos omething
                    }
                });
            });


            return map;
        };

由于我进行了多个异步 ajax 调用,因此我们假设其中 1 个需要很长时间才能执行。 这个 testMethod 是否有可能在 ajax 调用完成之前返回?

确实。 ajax 调用是异步的,因此代码将继续执行而无需等待成功/错误回调函数。

您有两个选择:

  1. 将您的 ajax 调用作为同步调用(更多信息在这里
  2. (推荐)使您的testMethod函数成为异步函数(更多信息在这里

但是(1º 选项)

不推荐将 async 属性设置为 false 并正在被删除(链接)。 如果你使用这个,包括 Firefox 和 Chrome 在内的许多浏览器已经开始在控制台中打印警告:

并遵循了2º选项的例子(更多关于JavaScript的承诺,在这里和Promise.All在这里):

 async function makeAjaxCall() { return new Promise((resolve) => { setTimeout(() => { // Just to make the makeAjaxCall 1 second slower; $.ajax({ url: 'http://www.mocky.io/v2/5e6ac7d32d0000db0c5fa686', type: 'GET', data: {}, success: function(data) { resolve(data); }, error: function(jqxhr, settings, exception) { resolve({ error: 'OMG an ERROR!'}); // dos omething } }) }, 1000); }); }; async function asynCall() { for(let i=0; i<10; i++) { // You can see in here that will wait 1 second before is going to the next ajax call const result = await makeAjaxCall(); console.log(result); } } // You can run all your calls in paralel by using the Promise.All like this async function promiseAll() { const ajaxCalls = []; for(let i=0; i<10; i++) { ajaxCalls.push(makeAjaxCall()); } //for this case, the calls will be made in parallel, which measn will take slight more than 1 second Promise.all(ajaxCalls).then(function(values) { // will print the array of values which contains the values of each ajax call console.log(values); }); } asynCall(); promiseAll();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暂无
暂无

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

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