CodexBloom - Programming Q&A Platform

Handling Multiple Promises with Different Resolutions in Node.js - advanced patterns

👀 Views: 79 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
javascript node.js async-await promises JavaScript

I'm a bit lost with I'm converting an old project and This might be a silly question, but I'm working on a Node.js application where I need to process multiple API requests concurrently, each returning promises that resolve at different times... I'm using `Promise.all()` to handle these promises, but I'm working with issues when one of them rejects. It seems that if any promise rejects, the entire batch fails, which is expected, but I would like to handle rejections differently to continue processing others. Here's a simplified version of my code: ```javascript const axios = require('axios'); const urls = ['https://api.example.com/data1', 'https://api.example.com/data2', 'https://api.example.com/data3']; const fetchData = async (url) => { const response = await axios.get(url); return response.data; }; const fetchAllData = async () => { const promises = urls.map(url => fetchData(url)); try { const results = await Promise.all(promises); console.log(results); } catch (behavior) { console.behavior('Failed to fetch data:', behavior.message); } }; fetchAllData(); ``` When one of the requests fails (for example, if an endpoint returns a 404 behavior), I receive the behavior message from the catch block, and no results are logged. I've tried using `Promise.allSettled()` instead, which seems to solve the scenario, but I'm unsure how to handle the results since I need only the fulfilled promises. Here's what I attempted with `Promise.allSettled()`: ```javascript const fetchAllDataSettled = async () => { const promises = urls.map(url => fetchData(url)); const results = await Promise.allSettled(promises); const fulfilledResults = results.filter(result => result.status === 'fulfilled').map(result => result.value); console.log(fulfilledResults); }; fetchAllDataSettled(); ``` This works, but I'm concerned about the extra complexity and performance implications of handling both fulfilled and rejected promises separately. Is there a more efficient way to manage this situation, or is `Promise.allSettled()` the best approach? Also, would it be safe to log the behavior messages for the rejected promises without crashing the whole process, and how can I do that neatly? My development environment is macOS. My development environment is Ubuntu. What's the best practice here? I'd love to hear your thoughts on this. Has anyone else encountered this?