When passing a dynamic array to a function in JavaScript that returns multiple promises, the best approach is to use Promise.all() to handle those promises. This ensures all promises are resolved (or rejected) before moving forward. Here’s a guide:
---
Example Scenario
You have a function processItem that processes individual items and returns a promise. You want to pass an array of items dynamically and return multiple promises.
Step-by-Step Solution
1. Use Promise.all() for Parallel Execution Promise.all() takes an array of promises and returns a single promise that resolves when all promises are resolved or rejects if one fails.
2. Handle Rejected Promises Gracefully If you want all promises to run regardless of individual failures, use Promise.allSettled():
Output:
3. Sequential Execution (if needed) If you need to process items sequentially instead of in parallel, use a for...of loop:
processAllItemsSequentially(items).then(results => console.log('Results:', results));
Output (with sequential timing):
Key Points
Promise.all() is best for parallel execution but will reject immediately if one promise fails.
Promise.allSettled() lets all promises complete regardless of failure.
Sequential execution can be implemented using for...of or a reduce chain.
Always handle errors gracefully, especially in dynamic arrays where failures are possible.
---
Example Scenario
You have a function processItem that processes individual items and returns a promise. You want to pass an array of items dynamically and return multiple promises.
Step-by-Step Solution
1. Use Promise.all() for Parallel Execution Promise.all() takes an array of promises and returns a single promise that resolves when all promises are resolved or rejects if one fails.
JavaScript:
const processItem = (item) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (item !== 'error') {
resolve(`Processed: ${item}`);
} else {
reject(`Failed to process: ${item}`);
}
}, 1000);
});
};
const processAllItems = async (items) => {
try {
const results = await Promise.all(items.map(item => processItem(item)));
return results; // All promises resolved
} catch (error) {
console.error(error); // Handle a rejected promise
throw error; // Optionally re-throw the error
}
};
const items = ['item1', 'item2', 'item3'];
processAllItems(items)
.then(results => console.log('Results:', results))
.catch(err => console.log('Error:', err));
Output:
Results: [ 'Processed: item1', 'Processed: item2', 'Processed: item3' ]
2. Handle Rejected Promises Gracefully If you want all promises to run regardless of individual failures, use Promise.allSettled():
JavaScript:
const processAllItems = async (items) => {
const results = await Promise.allSettled(items.map(item => processItem(item)));
return results; // Resolves with an array of statuses (fulfilled/rejected)
};
const items = ['item1', 'item2', 'error'];
processAllItems(items).then(results => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Item ${index} succeeded:`, result.value);
} else {
console.log(`Item ${index} failed:`, result.reason);
}
});
});
Output:
JavaScript:
Item 0 succeeded: Processed: item1
Item 1 succeeded: Processed: item2
Item 2 failed: Failed to process: error
3. Sequential Execution (if needed) If you need to process items sequentially instead of in parallel, use a for...of loop:
JavaScript:
const processAllItemsSequentially = async (items) => {
const results = [];
for (const item of items) {
try {
const result = await processItem(item);
results.push(result);
} catch (error) {
console.error('Error:', error);
results.push(error); // Optionally handle the error
}
}
return results;
};
processAllItemsSequentially(items).then(results => console.log('Results:', results));
Output (with sequential timing):
JavaScript:
Results: [ 'Processed: item1', 'Processed: item2', 'Failed to process: error' ]
---
Key Points
Promise.all() is best for parallel execution but will reject immediately if one promise fails.
Promise.allSettled() lets all promises complete regardless of failure.
Sequential execution can be implemented using for...of or a reduce chain.
Always handle errors gracefully, especially in dynamic arrays where failures are possible.