0 day streak
javascript / intermediate
Snippet

Managing Concurrent Batch Operations with Promise.allSettled and Reactive Progress

When triggering multiple concurrent async requests, `Promise.allSettled()` ensures all promises complete regardless of individual rejections. Iterating through the settled entries with `results.entries()` allows precise failure tracking and synchronous updates to reactive UI progress counters without halting on the first rejected promise.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { ref } from 'vue';
export function useBatchProcessor() {
const pendingCount = ref(0);
const failedTasks = ref([]);
async function executeBatch(tasks) {
pendingCount.value = tasks.length;
failedTasks.value = [];
const executionPromises = tasks.map(task => task());
const results = await Promise.allSettled(executionPromises);
for (const [index, result] of results.entries()) {
if (result.status === 'rejected') {
failedTasks.value.push({
taskId: index,
reason: result.reason instanceof Error ? result.reason.message : String(result.reason)
});
}
pendingCount.value -= 1;
}
return failedTasks.value.length === 0;
}
return { pendingCount, failedTasks, executeBatch };
}
vue
Breakdown
1
const results = await Promise.allSettled(executionPromises);
Waits for all concurrent async operations to either resolve or reject without throwing an early error.
2
for (const [index, result] of results.entries()) {
Iterates over indexed outcome objects containing status and either value or reason properties.
3
if (result.status === 'rejected') {
Checks the settled promise status to safely capture and structure rejected reasons.