Implementing Promise.race() in JavaScript

🚀 Day 21/100 – Implementing Promise.race() in JavaScript Today I explored another important Promise method: Promise.race() It returns the result of the first settled promise (either resolved or rejected). 🧠 Problem: Create a custom implementation of Promise.race(). ✅ Solution: function myPromiseRace(promises) { return new Promise((resolve, reject) => { promises.forEach((promise) => { Promise.resolve(promise) .then(resolve) .catch(reject); }); }); } // Example const p1 = new Promise((res) => setTimeout(() => res("First"), 1000)); const p2 = new Promise((res) => setTimeout(() => res("Second"), 500)); myPromiseRace([p1, p2]) .then((data) => console.log(data)) .catch((err) => console.error(err)); ✅ Output: Second (Because it resolves faster) 💡 Key Learnings: • Returns the first settled promise (resolve or reject) • Does NOT wait for all promises • Useful for timeouts and fallback strategies • Works well in race conditions 📌 Real World Usage: • API timeout handling • Loading fastest resource • Fallback mechanisms • Performance optimization Understanding Promise utilities helps in writing better async logic and handling real-world scenarios. I’m currently open to Frontend Developer opportunities (React / Next.js) and available for immediate joining. 📩 Email: bantykumar13365@gmail.com 📱 Mobile: 7417401815 If you're hiring or know someone who is, I’d love to connect. #OpenToWork #FrontendDeveloper #JavaScript #Promises #ReactJS #NextJS #ImmediateJoiner #100DaysOfCode

To view or add a comment, sign in

Explore content categories