Module 55 : Promises and .then/.catch Chaining Promises in javascript
1. What is a Promise in JavaScript?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Why use Promises?
To avoid callback hell
To handle asynchronous operations like API requests, file I/O, timeouts, etc.
To write cleaner, readable, and maintainable code
2. Promise Syntax
let promise = new Promise(function(resolve, reject) { // Asynchronous task });
✅ resolve(value)
Marks the promise as fulfilled with a result.
❌ reject(error)
Marks the promise as rejected with an error.
3. Using .then() and .catch()
promise .then(function(result) { // Handle success }) .catch(function(error) { // Handle error });
.then() handles success
.catch() handles failure
4. Chaining Promises
What is Chaining?
It means linking multiple .then() calls in sequence where the output of one .then() becomes input for the next.
Example
new Promise(function(resolve, reject) { setTimeout(() => resolve(10), 1000); }) .then(function(result) { console.log("First then:", result); // 10 return result * 2; }) .then(function(result) { console.log("Second then:", result); // 20 return result * 3; }) .then(function(result) { console.log("Third then:", result); // 60 }) .catch(function(error) { console.error("Error:", error); });
Each .then() returns a new Promise, allowing values to flow through each stage.
5. Fetching and Chaining Data
Objective: Fetch user data from an API and display name, then fetch posts for that user.
function getUser(userId) { return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`) .then(response => response.json()); } function getPostsByUser(userId) { return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`) .then(response => response.json()); } // Chain the calls getUser(1) .then(user => { console.log("User:", user.name); return getPostsByUser(user.id); }) .then(posts => { console.log("User's Posts:", posts.slice(0, 3)); // show 3 posts }) .catch(error => { console.error("Error occurred:", error); });
Notes:
Test network failure by disconnecting.
Try invalid user IDs to test error handling.
Add .finally() to see how it runs regardless of success/failure.
6. Nested vs Chained Promises
(Nested Promises):
getUser(1).then(user => { getPostsByUser(user.id).then(posts => { console.log(posts); }); });
Harder to read/debug
Leads to callback-like pyramid
(Chained Promises):
getUser(1) .then(user => getPostsByUser(user.id)) .then(posts => console.log(posts));
Cleaner
Each function handles a single task
Better separation of concerns
7. Benefits of Promises Based on Research
Improved readability over callbacks
Error bubbling: An error in any .then() will propagate to the nearest .catch()
Composability: Break complex tasks into smaller, reusable functions
Promises are the foundation of async/await, a modern syntax for async code
8. Exercises
Exercise 1: Create a Delay Function
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } delay(1000) .then(() => console.log("1 second passed")) .then(() => delay(1000)) .then(() => console.log("2 seconds passed")) .then(() => delay(1000)) .then(() => console.log("3 seconds passed"));
Exercise 2: Chain Multiple Async Math Operations
function add(a, b) { return new Promise(resolve => setTimeout(() => resolve(a + b), 500)); } function multiply(a, b) { return new Promise(resolve => setTimeout(() => resolve(a * b), 500)); } add(5, 10) .then(result => { console.log("Sum:", result); return multiply(result, 2); }) .then(result => console.log("Final Result:", result)) .catch(error => console.error(error));
9. Summary
Concept
Description
Promise
Handles async operations with resolve/reject
.then()
Handles successful resolution
.catch()
Handles errors
Chaining
Pass result from one .then() to another
Avoid Nesting
Prefer chaining over nesting
Lab Use
Ideal for API calls, async workflows
Expert Insight
Promises simplify complex async logic
Build a Weather Fetcher Chain
Get user’s city from a mock function
Fetch weather data using chained promises
Handle errors and show results in the console
function getCity() { return new Promise((resolve) => { setTimeout(() => resolve("Mumbai"), 500); }); } function getWeather(city) { return fetch(`https://wttr.in/${city}?format=j1`) .then(response => response.json()); } getCity() .then(city => { console.log("City:", city); return getWeather(city); }) .then(weather => { console.log("Temperature:", weather.current_condition[0].temp_C + "°C"); }) .catch(err => { console.error("Failed to fetch weather data:", err); });
No comments:
Post a Comment