✅ Logical Operators in JavaScript – Complete Guide with Real Examples

“Why should I use Promises instead of callbacks?”
This is one of the most frequently asked questions by JavaScript learners. In this guide, we’ll answer it completely — with real-world examples, visuals, and deep explanation.
A Promise is a built-in JavaScript object that represents the eventual completion (or failure) of an asynchronous operation — and its resulting value.
That’s exactly how Promises work in JavaScript. They’re a smarter way to deal with asynchronous code, without falling into callback hell.
Before Promises, developers used callback functions to handle async tasks like data fetching or timers.
But as tasks grew in complexity, callbacks became nested and messy:
getData(function(result1) {
processData(result1, function(result2) {
display(result2, function() {
console.log("Done!");
});
});
});
This is known as Callback Hell, and it quickly becomes hard to debug or maintain.
Promises solve this problem by offering a clean, chainable syntax.
const myPromise = new Promise((resolve, reject) => {
// Simulate async task
setTimeout(() => {
const success = true;
if (success) {
resolve("✅ Data loaded successfully!");
} else {
reject("❌ Failed to load data.");
}
}, 1000);
});
myPromise
.then((response) => console.log(response))
.catch((error) => console.log(error));
new Promise
creates a new promise objectresolve
and reject
setTimeout
.then()
handles the resolved value.catch()
handles any errorfetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log("Post title:", data.title))
.catch((error) => console.error("Error:", error));
✅ Output:
Post title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
This is the modern way of doing AJAX-like calls using Promises
and the fetch()
API.
State | Meaning |
---|---|
Pending | The initial state — not yet fulfilled or rejected |
Fulfilled | The async operation completed successfully |
Rejected | The async operation failed |
getUser()
.then(user => getPosts(user.id))
.then(posts => displayPosts(posts))
.catch(error => console.error("Something went wrong", error));
Each .then()
receives the result of the previous step — just like piping water through different stages.
function fetchData(callback) {
setTimeout(() => {
callback("π Data from server");
}, 1000);
}
fetchData((data) => {
console.log(data);
});
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("π Data from server");
}, 1000);
});
}
fetchData().then(data => console.log(data));
Promises are better because:
const promise1 = fetch("https://jsonplaceholder.typicode.com/users");
const promise2 = fetch("https://jsonplaceholder.typicode.com/posts");
Promise.all([promise1, promise2])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(([users, posts]) => {
console.log("Users:", users.length);
console.log("Posts:", posts.length);
})
.catch(error => console.error("Failed to load data:", error));
Great when you want all tasks done before proceeding — like loading user and post data at once.
async function loadData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
console.log("Async Data:", data);
} catch (error) {
console.error("Error:", error);
}
}
The async/await
syntax makes Promises even cleaner and easier to use — like writing synchronous code!
Feature | Callback | Promise |
---|---|---|
Syntax | Nested, messy | Chainable, clean |
Error Handling | Manual | .catch() |
Readability | Poor | Good |
Composition | Hard | Easy |
Compatibility | Old Style | Modern JavaScript (ES6+) |
JavaScript Promises are the foundation of modern async programming. Whether you’re fetching data, chaining multiple tasks, or handling real-world operations — Promises help you write clean, scalable, and reliable code.
π§ Check out my YouTube video here:
π (Embed your Promise tutorial video)
“What was your biggest challenge while learning Promises in JavaScript?
Let me know in the comments!”
Comments
Post a Comment