我們一起聊聊如何使用 Promise.allSettled()判斷接口請(qǐng)求完畢
1. 如何使用 Promise.allSettled()判斷接口請(qǐng)求完畢
使用 Promise.allSettled() 來判斷多個(gè)接口請(qǐng)求是否全部完成是非常直觀和直接的。
Promise.allSettled() 方法會(huì)等待所有的 Promise 對(duì)象都完成(無論是成功還是失敗),然后返回一個(gè)包含每個(gè) Promise 結(jié)果的數(shù)組。
每個(gè)結(jié)果對(duì)象都包含了 status 屬性,可以是 "fulfilled"(成功)或 "rejected"(失?。?,以及 value 或 reason 屬性,分別表示成功或失敗時(shí)的結(jié)果。
下面是一個(gè)具體的示例,展示如何使用 Promise.allSettled() 來判斷多個(gè)接口請(qǐng)求是否全部完成:
1.1. 示例代碼
假設(shè)我們需要從三個(gè)不同的 API 端點(diǎn)獲取數(shù)據(jù),并在所有請(qǐng)求完成后執(zhí)行一些操作。
1.1.1. 定義請(qǐng)求函數(shù)
首先,定義一個(gè)函數(shù)來發(fā)起請(qǐng)求,并返回一個(gè) Promise 對(duì)象。
function fetchAPI(url) {
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
}
1.1.2. 使用 Promise.allSettled()
接下來,使用 Promise.allSettled() 來等待所有的請(qǐng)求完成。
const apiUrls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
];
const fetchRequests = apiUrls.map(url => fetchAPI(url));
Promise.allSettled(fetchRequests)
.then(results => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Request ${index + 1} succeeded:`, result.value);
} else {
console.error(`Request ${index + 1} failed:`, result.reason);
}
});
// 所有請(qǐng)求完成,可以在這里執(zhí)行其他操作
console.log('All requests have been processed.');
})
.catch(error => {
console.error('An unexpected error occurred:', error);
});
1.2. 代碼解釋
- 定義請(qǐng)求函數(shù):
- fetchAPI 函數(shù)接收一個(gè) URL 參數(shù),使用 fetch 發(fā)起請(qǐng)求,并返回一個(gè) Promise。
- 如果請(qǐng)求成功,Promise 會(huì)被解析為 JSON 數(shù)據(jù)。
- 如果請(qǐng)求失敗,Promise 會(huì)被拒絕,并拋出錯(cuò)誤。
- 使用 Promise.allSettled():
創(chuàng)建一個(gè)包含所有請(qǐng)求的數(shù)組 fetchRequests。
使用 Promise.allSettled() 等待所有請(qǐng)求完成。
results 數(shù)組包含了每個(gè)請(qǐng)求的結(jié)果對(duì)象,其中每個(gè)對(duì)象都有 status 和 value 或 reason 屬性。
根據(jù)每個(gè)請(qǐng)求的狀態(tài),打印成功或失敗的信息。
1.3. 總結(jié)
通過使用 Promise.allSettled(),你可以確保在所有請(qǐng)求完成之后再執(zhí)行后續(xù)的操作。
這種方法的好處在于它能處理成功和失敗的情況,并且提供了每個(gè)請(qǐng)求的完整結(jié)果,使得你可以根據(jù)每個(gè)請(qǐng)求的狀態(tài)來做出相應(yīng)的處理。
如果你需要在所有請(qǐng)求完成之后執(zhí)行某些操作,可以將這些操作放在 Promise.allSettled() 的回調(diào)函數(shù)中。
此外,你還可以根據(jù)實(shí)際需求調(diào)整錯(cuò)誤處理邏輯,例如記錄錯(cuò)誤信息或重新發(fā)起失敗的請(qǐng)求。