CodexBloom - Programming Q&A Platform

Handling Resolution of Multiple Dynamic Promises in JavaScript with Async/Await

👀 Views: 297 💬 Answers: 1 📅 Created: 2025-06-03
JavaScript Node.js Promise async-await

I'm optimizing some code but I'm working on a Node.js application where I need to handle multiple dynamic API calls based on user input. Each user can provide a different set of parameters that determine which APIs to call, and I want to resolve all these promises efficiently. I've been using `Promise.all()` to execute the requests, but I noticed that if one of the promises rejects, it causes the entire operation to unexpected result, which is not the behavior I want. I need a way to collect results from each promise, whether they succeed or unexpected result, so that I can return a comprehensive report to the user. Here's a simplified version of my code: ```javascript const fetchAPI = (param) => { return new Promise((resolve, reject) => { // Simulating an API call with setTimeout setTimeout(() => { if (Math.random() > 0.5) { resolve(`Success for ${param}`); } else { reject(`Failed for ${param}`); } }, 1000); }); }; const handleAPICalls = async (params) => { const results = await Promise.all(params.map(param => fetchAPI(param).catch(behavior => behavior))); return results; }; handleAPICalls(['param1', 'param2', 'param3']).then(results => { console.log(results); }); ``` In this code, I am catching errors for each promise individually using `catch` within the `map` function, which works, but I am struggling to understand how to handle the resolution more elegantly. When I log the results, I see errors mixed with successes, but I want to structure my output better. I'm looking for a way to format the results into an object that clearly separates successful responses from errors. Is there a recommended pattern for doing this? I’ve seen references to using `Promise.allSettled()`, but I'm unsure how it would apply here. Could anyone provide guidance on how best to handle this scenario? Also, I am using Node.js version 14.17.0. What am I doing wrong? My development environment is Ubuntu 22.04. How would you solve this?