Promise.all() vs Promise.race() in JavaScript

Day 11/50 – JavaScript Interview Question? Question: What is the difference between Promise.all() and Promise.race()? Simple Answer: Promise.all() waits for all promises to resolve (or one to reject) and returns an array of results. Promise.race() returns as soon as the first promise settles (resolves or rejects), ignoring the others. 🧠 Why it matters in real projects: Use Promise.all() when you need multiple API calls to complete before proceeding (like fetching user data and their posts). Use Promise.race() for implementing timeouts or choosing the fastest response from multiple sources. 💡 One common mistake: Not realizing that Promise.all() fails fast—if any promise rejects, the entire operation fails immediately, even if other promises are still pending. 📌 Bonus: // Promise.all - all must succeed const results = await Promise.all([ fetch('/api/user'), fetch('/api/posts'), fetch('/api/comments') ]); // If any fails, all fail // Promise.race - first one wins const result = await Promise.race([ fetch('/api/data'), new Promise((_, reject) => setTimeout(() => reject('Timeout'), 5000) ) ]); // Implements a 5-second timeout // Use Promise.allSettled() to get all results regardless of failures #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories