Understanding Promise Chaining in JavaScript

🔍 JavaScript Behavior You Might Have Seen (Promise Chaining) You write this: Promise.resolve(1) .then((res) => { console.log(res); return res + 1; }) .then((res) => { console.log(res); return res + 1; }); 👉 Output: 1 2 Now try this 👇 Promise.resolve(1) .then((res) => { console.log(res); }) .then((res) => { console.log(res); }); 👉 Output: 1 undefined 🤯 Same chain… different result… why? This happens because of Promise Chaining 📌 What is Promise Chaining? 👉 It’s the process of passing the result from one .then() to the next 📌 What’s happening here? ✔ If you return a value: 👉 It goes to the next .then() ✔ If you don’t return anything: 👉 undefined is passed So this: .then((res) => { console.log(res); }) 👉 is actually: .then((res) => { console.log(res); return undefined; }) 📌 Important rule: 👉 Every .then() returns a new Promise 📌 Bonus case 👇 .then((res) => { return Promise.resolve(res + 1); }) 👉 Next .then() waits for it automatically 💡 Takeaway: ✔ Return value → passed to next .then() ✔ No return → undefined ✔ Returning Promise → waits automatically 👉 Promise chain is all about “what you return” 🔁 Save this for later 💬 Comment “promise” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer

I'm more of an "async/await" man, myself 😅

Like
Reply

To view or add a comment, sign in

Explore content categories