在 jQuery 的 each
函数中处理异步操作,可以通过以下方法实现:
Promise.all
:当有多个异步操作时,可以使用 Promise.all
等待所有异步操作完成后再执行后续代码。const asyncOperation1 = $.ajax({ url: 'someUrl1' });
const asyncOperation2 = $.ajax({ url: 'someUrl2' });
Promise.all([asyncOperation1, asyncOperation2])
.then((results) => {
const [data1, data2] = results;
// 在这里处理异步操作的结果
})
.catch((error) => {
console.error('Error:', error);
});
async/await
:将 each
函数改为异步函数,并使用 await
等待异步操作完成。async function handleAsyncOperations(array) {
for (const item of array) {
const result = await $.ajax({ url: item.url });
// 在这里处理异步操作的结果
}
}
const items = [
{ url: 'someUrl1' },
{ url: 'someUrl2' },
];
handleAsyncOperations(items);
请注意,使用 async/await
时需要确保在异步函数内部使用 await
,并且在调用异步函数时不要使用 return
,而是使用 resolve
或 reject
。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:jQuery each中如何处理异步回调