Medium
Understanding Promise.all with Retry Logic: Handling Concurrent API Requests in JavaScript
You're building a system to handle concurrent API requests with retries. What will be logged after executing this code?
1class RequestHandler {2 static async makeRequest(id, attempts = 3, delay = 1000) {3 for (let i = 0; i < attempts; i++) {4 try {5 // Simulate API call6 const success = await this.simulateRequest(id, i);7 if (success) {8 return `Request ${id} succeeded on attempt ${i + 1}`;9 }10 } catch (error) {11 if (i === attempts - 1) throw error;12 await new Promise(resolve => setTimeout(resolve, delay));13 }14 }15 throw new Error(`Failed after ${attempts} attempts`);16 }1718 static async simulateRequest(id, attempt) {19 // Succeed on second attempt for even IDs, first attempt for odd IDs20 return id % 2 === 0 ? attempt === 1 : attempt === 0;21 }22}2324async function processRequests() {25 try {26 const results = await Promise.all([27 RequestHandler.makeRequest(1),28 RequestHandler.makeRequest(2)29 ]);30 return results;31 } catch (error) {32 return ['Error occurred'];33 }34}3536processRequests().then(console.log);