在 jQuery 的 each
函數(shù)中處理異步回調(diào)時(shí),可以使用 Promise.all
來(lái)確保所有異步操作完成后再執(zhí)行后續(xù)代碼。下面是一個(gè)示例:
// 假設(shè)我們有一個(gè)包含異步操作的數(shù)組
const asyncOperations = [
() => $.ajax({ url: 'someUrl1', dataType: 'json' }),
() => $.ajax({ url: 'someUrl2', dataType: 'json' }),
// ...
];
// 使用 Promise.all 來(lái)處理所有異步操作
Promise.all(asyncOperations.map(operation => operation()))
.then(results => {
console.log('所有異步操作已完成');
console.log('結(jié)果1:', results[0]);
console.log('結(jié)果2:', results[1]);
// ...
})
.catch(error => {
console.error('發(fā)生錯(cuò)誤:', error);
});
在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)包含異步操作的數(shù)組 asyncOperations
。然后,我們使用 Promise.all
和 map
函數(shù)來(lái)處理數(shù)組中的每個(gè)異步操作。Promise.all
會(huì)等待所有異步操作完成,然后返回一個(gè)包含所有結(jié)果的數(shù)組。最后,我們使用 then
和 catch
處理成功和失敗的情況。