Skip to content

(feat) Day 26 - Common Mistakes #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,4 @@ I am an independent educator and open-source enthusiast who creates meaningful p
- **`Day 23: JavaScript Promises: Zero to Hero`** - [Watch Video](https://youtu.be/R52MdtIW3rs) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-23/README.md)
- **`Day 24: Master JavaScript async/await & Simplify Promises Like a PRO`** - [Watch Video](https://youtu.be/WQdCffdPPKI) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-24/README.md)
- **`Day 25: JavaScript fetch() Explained Like Never Before`** - [Watch Video](https://www.youtube.com/watch?v=G3oPZSvrO9w) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-25/README.md)
- **`Day 26: 6 Common Mistakes with JavaScript Promises & Async Code`** - [Watch Video](https://youtu.be/c_zcXUz1neo) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-26/README.md)
31 changes: 31 additions & 0 deletions day-26/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Day 26 - 40 Days of JavaScript - Common Mistakes

## **🎯 Goal of This Lesson**

- ✅ Introduction
- ✅ Promises and Loop
- ✅ Chain or No-Chain
- ✅ Not Handling Errors
- ✅ Missing Callback
- ✅ Synchronous Operation
- ✅ Unnecessary try/catch
- ✅ Quick Recap

## 🫶 Support

Your support means a lot.

- Please SUBSCRIBE to [tapaScript YouTube Channel](https://youtube.com/tapasadhikary) if not done already. A Big Thank You!
- Liked my work? It takes months of hard work to create quality content and present it to you. You can show your support to me with a STAR(⭐) to this repository.

> Many Thanks to all the `Stargazers` who have supported this project with stars(⭐)

### 🤝 Sponsor My Work

I am an independent educator and open-source enthusiast who creates meaningful projects to teach programming on my YouTube Channel. **You can support my work by [Sponsoring me on GitHub](https://github.com/sponsors/atapas) or [Buy Me a Cofee](https://buymeacoffee.com/tapasadhikary)**.

## Video

Here is the video for you to go through and learn:

[![day-26](./banner.png)](https://youtu.be/c_zcXUz1neo "Video")
Binary file added day-26/banner.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions day-26/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Common Promise Mistakes</title>
<script defer src="./index.js"></script>
</head>
<body>
<h1>40 Days of JavaScript - Common Promise Mistakes</h1>
</body>
</html>
201 changes: 201 additions & 0 deletions day-26/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
// Mistake 1 - Looping with Promises

const ids = ["1", "2", "3", "4"];

const fetchData = (id) => {
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
};

const loopFetches = () => {
for (let i = 0; i < ids.length; i++) {
console.log(`*** Fetching details of ${ids[i]} ***`);
const response = fetchData(ids[i]);
response.then((response) => {
response.json().then((data) => {
console.log(
`
Name: ${data?.name}
Company:${data?.company?.name}
Address: ${data?.address?.city}
`
);
});
});
}
};

// loopFetches();

const loopFetchesAsync = async () => {
for (let i = 0; i < ids.length; i++) {
console.log(`=== Fetching details of ${ids[i]} ===`);
const response = await fetchData(ids[i]);
const data = await response.json();
console.log(
`
Name: ${data?.name}
Company:${data?.company?.name}
Address: ${data?.address?.city}
`
);
}
};

// loopFetchesAsync();

const loopAll = async () => {
const responses = await Promise.allSettled(ids.map((id) => fetchData(id)));
const data = await Promise.allSettled(
responses.map((response) => response.value.json())
);
console.log(data);
data.map((userInfo) => {
const user = userInfo.value;
console.log(`*** Fetching details of ${user?.name} ***`);
console.log(
`
Name: ${user?.name}
Company:${user?.company?.name}
Address: ${user?.address?.city}
`
);
});
};

loopAll();

// Mistake 2 - Promise Chain vs. No Chain

// Chain
const ten = new Promise((resolve, reject) => {
resolve(10);
});

ten.then((result) => {
// returns 20
return result + 10;
})
.then((result) => {
// returns 200
return result * 10;
})
.then((result) => {
// returns 190
return result - 10;
})
.then((result) => {
// logs 190 in console
console.log(result);
});

// No Chain
ten.then((result) => {
// returns 20
return result + 10;
});
ten.then((result) => {
// returns 100
return result * 10;
});
ten.then((result) => {
// returns 0
return result - 10;
});
ten.then((result) => {
// logs 10 in the console.
console.log(result);
});

// Mistake 3 - (Not)Handling Errors with Promises

const oddEven = (num) => {
return new Promise((resolve, reject) => {
if (num % 2 === 0) {
resolve("Even");
} else {
reject(new Error("Odd"));
}
});
};

oddEven(10).then((result) => {
console.log(result);
});

oddEven(11)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.error(err.message);
});

// Mistake 4 - Missing a function in .then() handler

const hello = Promise.resolve("Hello");
hello.then("World").then((result) => console.log(result));
hello.then(() => "World").then((result) => console.log(result));

// Mistake 5 - Using Promises for Synchronous Operations
const cache = {
"tapas@email.com": {
name: "Tapas Adhikary",
org: "tapaScript",
},
};

const getDataV1 = (email) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const userFromCache = cache[email];
if (!userFromCache) {
// Make the call to fetch user data
// update cache
console.log("Make the call and update cache");
} else {
console.log(`User details ${JSON.stringify(userFromCache)}`);
}
}, 2000);
});
};

getDataV1("tapas@email.com");

const getDataV2 = (email) => {
const userFromCache = cache[email];
if (userFromCache) {
console.log(`User details ${JSON.stringify(userFromCache)}`);
} else {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Make the call and update cache");
}, 2000);
});
}
};

getDataV2("tapas@email.com");

// Mistake 6 - Using unnecessary try-catch with promises

// Redundant try-catch
new Promise((resolve, reject) => {
try {
const value = getValue();
// do something with value
resolve(value);
} catch (e) {
reject(e);
}
})
.then((result) => console.log(result))
.catch((error) => console.log(error));

// Better Way
new Promise((resolve, reject) => {
const value = getValue();
// do something with value
resolve(value);
})
.then((result) => console.log(result))
.catch((error) => console.log(error));