gpt4 book ai didi

javascript - jQuery 异步 ajax 调用

转载 作者:行者123 更新时间:2023-12-01 00:01:59 25 4
gpt4 key购买 nike

我有以下带有列表的代码,并且对于该列表中的每个元素,执行 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 调用作为同步调用(更多信息 here )
  2. (推荐)使您的 testMethod 函数成为异步函数(更多信息 here )

但是(1°选项):

Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

下面是 2° 选项的示例(更多关于 here 中的 javascript Promise 和 here 中的 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>

关于javascript - jQuery 异步 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60662901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com