JS中Promise.all 和 Promise.allsettled區(qū)別小結
更新時間:2026年05月28日 16:13:05 作者:代碼獵人
本文主要介紹了JS中Promise.all 和 Promise.allsettled區(qū)別小結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
核心區(qū)別對比表
| 特性 | Promise.all | Promise.allSettled |
|---|---|---|
| 成功條件 | 所有 Promise 都成功 | 所有 Promise 都完成(無論成功失敗) |
| 失敗條件 | 任何一個 Promise 失敗就立即失敗 | 永遠不會失敗 |
| 返回值 | 成功值數組 | 狀態(tài)對象數組 |
| 設計目的 | 需要所有結果都成功才能繼續(xù) | 需要知道每個 Promise 的最終狀態(tài) |
| ES版本 | ES6 (2015) | ES2020 |
| 使用場景 | 并行依賴的操作 | 獨立的并行操作 |
詳細對比
1.行為差異
Promise.all - 全有或全無
const p1 = Promise.resolve('成功1');
const p2 = Promise.reject('錯誤2'); // 這個會失敗
const p3 = Promise.resolve('成功3');
Promise.all([p1, p2, p3])
.then(results => {
console.log('全部成功:', results);
})
.catch(error => {
console.log('有一個失敗:', error); // 輸出: "錯誤2"
// p1和p3的結果被丟棄!
});
- 只要有一個失敗,立即失敗
- 其他 Promise 的結果會被丟棄
Promise.allSettled - 全部完成
const p1 = Promise.resolve('成功1');
const p2 = Promise.reject('錯誤2');
const p3 = Promise.resolve('成功3');
Promise.allSettled([p1, p2, p3])
.then(results => {
console.log('全部完成:');
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`p${index + 1}: 成功 - ${result.value}`);
} else {
console.log(`p${index + 1}: 失敗 - ${result.reason}`);
}
});
});
// 輸出:
// 全部完成:
// p1: 成功 - 成功1
// p2: 失敗 - 錯誤2
// p3: 成功 - 成功3
- 等待所有 Promise 完成
- 返回每個 Promise 的完整狀態(tài)信息
2.返回值結構不同
Promise.all 返回值
// 成功時返回: [value1, value2, ...]
Promise.all([Promise.resolve(1), Promise.resolve(2)])
.then(values => console.log(values)); // [1, 2]
// 失敗時返回: 第一個錯誤
Promise.all([Promise.resolve(1), Promise.reject('錯誤')])
.catch(error => console.log(error)); // "錯誤"
Promise.allSettled 返回值
Promise.allSettled([
Promise.resolve(1),
Promise.reject('錯誤'),
Promise.resolve(3)
])
.then(results => {
console.log(results);
/*
[
{ status: 'fulfilled', value: 1 },
{ status: 'rejected', reason: '錯誤' },
{ status: 'fulfilled', value: 3 }
]
*/
});
3.實際應用場景
適合 Promise.all 的場景
// 場景1: 需要所有數據才能渲染頁面
async function loadDashboard() {
try {
const [user, orders, notifications] = await Promise.all([
fetchUser(),
fetchOrders(),
fetchNotifications()
]);
// 所有數據都成功才渲染
renderDashboard({ user, orders, notifications });
} catch (error) {
// 任何一個失敗就顯示錯誤頁面
showErrorPage('加載數據失敗');
}
}
// 場景2: 并行執(zhí)行但有依賴關系
async function processOrder(orderId) {
const [order, inventory, payment] = await Promise.all([
getOrder(orderId),
checkInventory(orderId),
verifyPayment(orderId)
]);
// 三個檢查都通過才能繼續(xù)
return { order, inventory, payment };
}
適合 Promise.allSettled 的場景
// 場景1: 批量操作,需要知道每個結果
async function sendNotifications(users) {
const results = await Promise.allSettled(
users.map(user => sendNotification(user))
);
const successful = results
.filter(r => r.status === 'fulfilled')
.map(r => r.value);
const failed = results
.filter(r => r.status === 'rejected')
.map(r => r.reason);
console.log(`發(fā)送成功: ${successful.length}, 失敗: ${failed.length}`);
return { successful, failed };
}
// 場景2: 多源數據獲取,哪個快用哪個
async function getDataFromMultipleSources() {
const results = await Promise.allSettled([
fetchFromPrimaryAPI().catch(() => null), // 主API
fetchFromBackupAPI1().catch(() => null), // 備份API1
fetchFromBackupAPI2().catch(() => null) // 備份API2
]);
// 使用第一個成功的結果
for (const result of results) {
if (result.status === 'fulfilled' && result.value) {
return result.value;
}
}
throw new Error('所有數據源都失敗了');
}
// 場景3: 清理操作,無論單個成功失敗都要繼續(xù)
async function cleanupResources(resources) {
const cleanupResults = await Promise.allSettled(
resources.map(resource => resource.cleanup())
);
// 記錄所有清理結果,但不中斷流程
logCleanupResults(cleanupResults);
}
4.錯誤處理差異
// 使用 Promise.all 的錯誤處理
Promise.all([task1(), task2(), task3()])
.then(([result1, result2, result3]) => {
// 成功處理
})
.catch(error => {
// 任何一個失敗都會到這里
// 但不知道哪些成功了,哪些失敗了
console.error('某個任務失敗:', error);
});
// 使用 Promise.allSettled 的錯誤處理
Promise.allSettled([task1(), task2(), task3()])
.then(results => {
const errors = results
.filter(r => r.status === 'rejected')
.map(r => r.reason);
const successes = results
.filter(r => r.status === 'fulfilled')
.map(r => r.value);
if (errors.length > 0) {
console.log(`${errors.length} 個任務失敗,但繼續(xù)處理成功的`);
// 可以繼續(xù)處理 successes
}
return { successes, errors };
});
5.互相模擬實現
// 用 Promise.allSettled 模擬 Promise.all
function promiseAll(promises) {
return Promise.allSettled(promises)
.then(results => {
const rejected = results.find(r => r.status === 'rejected');
if (rejected) {
throw rejected.reason; // 拋出第一個錯誤
}
return results.map(r => r.value); // 返回所有值
});
}
// 用 Promise.all 模擬 Promise.allSettled(不完美)
function promiseAllSettled(promises) {
// 為每個 Promise 添加錯誤處理,確保不會拋出
const wrappedPromises = promises.map(p =>
Promise.resolve(p).then(
value => ({ status: 'fulfilled', value }),
reason => ({ status: 'rejected', reason })
)
);
return Promise.all(wrappedPromises);
}
總結選擇建議
使用Promise.all當:
- 所有 Promise 必須都成功才能繼續(xù)
- 操作有強依賴關系
- 一個失敗意味著整個操作失敗
- 需要快速失敗機制
使用Promise.allSettled當:
- 需要知道每個 Promise 的最終狀態(tài)
- 操作是獨立的,一個失敗不影響其他
- 需要收集所有結果(成功和失?。?/li>
- 實現降級機制或備用方案
- 執(zhí)行清理或日志記錄操作
簡單記憶:
- Promise.all = "全部成功才算成功"
- Promise.allSettled = "全部完成就是成功"
到此這篇關于JS中Promise.all 和 Promise.allsettled區(qū)別小結的文章就介紹到這了,更多相關JS中Promise.all 和 Promise.allsettled內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
用js代碼和插件實現wordpress雪花飄落效果的四種方法
這篇文章主要介紹了用js代碼和插件實現wordpress雪花飄落效果的四種方法,需要的朋友可以參考下2014-12-12

