JavaScript Promises Explained for Beginners and Advanced Developers
JavaScript Promises are one of the most important asynchronous concepts in modern web development. If you are preparing for frontend interviews, learning JavaScript, or trying to understand API handling in real projects, Promises help you manage async operations in a clean and powerful way.
हिंदी में:
JavaScript Promise modern development ka ek bahut important concept hai. Agar aap interview ki tayari kar rahe hain, JavaScript seekh rahe hain, ya real project me API calls aur asynchronous operations samajhna chahte hain, to Promises aapko async code ko clean aur better way me handle karna sikhate hain.
What is a Promise in JavaScript?
- A Promise is an object that represents the future result of an asynchronous operation.
- It tells us whether an async task will complete successfully or fail later.
- It is commonly used for API calls, timers, and data fetching.
In simple words, a Promise is like a placeholder for a value that will come in the future. JavaScript does not wait for the task to finish. Instead, it continues running other code and handles the result when it arrives.
हिंदी में समझें:
Promise ek object hota hai jo future me aane wale result ko represent karta hai. Jab koi async task hota hai, jaise API call, to result turant nahi milta. Promise batata hai ki result baad me milega ya error aa sakta hai.
Real-world example:
Jab aap online food order karte ho, order abhi place hota hai but delivery baad me hoti hai. Ye future result Promise jaisa hai.
const promise = new Promise((resolve, reject) => {
resolve("Success");
});
Promise States: Pending, Fulfilled, Rejected
- Pending → operation is still in progress
- Fulfilled → operation completed successfully
- Rejected → operation failed
Every Promise starts in the pending state. Once the task is done, it becomes either fulfilled or rejected. After that, its state cannot change again.
हिंदी में:
Har Promise pehle pending state me hota hai. Jab kaam successful ho jata hai to fulfilled ho jata hai, aur agar error aa jaye to rejected ho jata hai. Ek baar state change ho gayi to phir dobara change nahi hoti.
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data fetched");
} else {
reject("Something went wrong");
}
});
then(), catch(), and finally()
- .then() handles success
- .catch() handles errors
- .finally() always runs
These methods are used to react to the final result of a Promise. They make async code easier to understand and separate success flow from error flow.
हिंदी में:
.then() success ke liye hota hai, .catch() error handle karta hai, aur .finally() dono case me chalta hai. Jaise loader hide karna ya cleanup karna.
fetchData()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("Request completed");
});
Why do we use Promises?
- To write clean asynchronous code
- To avoid callback hell
- To improve readability and maintenance
- To handle success and errors properly
Promises solve the problem of deeply nested callbacks. They make async flow more structured and professional.
हिंदी में:
Promises ka main fayda ye hai ki ye callback hell ko avoid karte hain. Code zyada clean, readable aur maintainable ho jata hai.
Old Callback Style
login(() => {
getUser(() => {
getOrders(() => {
console.log("Done");
});
});
});
Promise Style
login()
.then(getUser)
.then(getOrders)
.then(() => console.log("Done"))
.catch(console.error);
Promise Chaining
- Multiple async operations can run step by step
- Each .then() can pass data to the next
- This creates a cleaner async sequence
Promise chaining is useful when one task depends on the output of another task.
हिंदी में:
Promise chaining ka matlab hai ek async task ke result ko next task me use karna. Isse step-by-step flow clean tarike se banta hai.
getUser()
.then((user) => {
return getOrders(user.id);
})
.then((orders) => {
console.log(orders);
})
.catch((err) => {
console.log(err);
});
Why return is important in then()
- If you do not return anything, the next .then() gets undefined
- If you return a Promise, the next .then() waits for it
This is a very common interview question and a very common bug in real applications.
हिंदी में:
Agar aap .then() ke andar return nahi karte, to next .then() ko undefined milta hai. Isliye chaining me return bahut important hota hai.
Wrong
Promise.resolve(10)
.then((value) => {
console.log(value);
})
.then((result) => {
console.log(result); // undefined
});
Correct
Promise.resolve(10)
.then((value) => {
return value * 2;
})
.then((result) => {
console.log(result); // 20
});
Promise.all()
- Runs multiple Promises in parallel
- Returns results when all Promises succeed
- If one Promise fails, the whole operation fails
Use Promise.all() when you need all results together, such as loading users, posts, and comments at the same time.
हिंदी में:
Promise.all() tab use hota hai jab aapko multiple async results ek saath chahiye hote hain. Lekin agar ek bhi Promise fail ho gaya, to pura Promise.all fail ho jata hai.
Promise.all([
Promise.resolve("Users"),
Promise.resolve("Posts"),
Promise.resolve("Comments")
])
.then((results) => {
console.log(results);
})
.catch((err) => {
console.log(err);
});
Promise.race(), Promise.allSettled(), and Promise.any()
- Promise.race() returns the first settled Promise
- Promise.allSettled() returns all results with status
- Promise.any() returns the first successful Promise
These methods are useful in advanced async logic, timeouts, reporting, and fallback systems.
हिंदी में:
Promise.race() sabse pehle settle hone wala result deta hai. Promise.allSettled() sabka status deta hai. Promise.any() pehla successful Promise return karta hai.
Promise.race([
new Promise((resolve) => setTimeout(() => resolve("Fast"), 100)),
new Promise((resolve) => setTimeout(() => resolve("Slow"), 500))
]).then((result) => {
console.log(result);
});
Promise.allSettled([
Promise.resolve("Done"),
Promise.reject("Failed")
]).then((results) => {
console.log(results);
});
Promise.any([
Promise.reject("Error 1"),
Promise.resolve("Success"),
Promise.reject("Error 2")
]).then((result) => {
console.log(result);
});
Promises with async/await
- async/await is built on top of Promises
- It makes async code easier to read
- It is widely used in modern JavaScript applications
async/await gives Promise-based code a cleaner syntax and makes complex async workflows easier to manage.
हिंदी में:
async/await Promise ka modern syntax hai. Ye code ko zyada readable aur simple bana deta hai, especially jab multiple async steps hote hain.
async function getData() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await res.json();
console.log(data);
} catch (err) {
console.log(err);
}
}
Microtask Queue and Promise Execution Order
- Promise callbacks go into the microtask queue
- Microtasks run before macrotasks like setTimeout
- This is a very popular advanced interview topic
Even if setTimeout has 0 delay, Promise callbacks usually run first because the microtask queue has higher priority in the event loop.
हिंदी में:
Promise ke callbacks microtask queue me jaate hain, aur microtask queue setTimeout jaisi macrotask queue se pehle execute hoti hai. Isliye Promise ka output pehle aata hai.
setTimeout(() => console.log("setTimeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("Hello");
Output:
Hello
Promise
setTimeout
Quick Summary
- A Promise represents the future result of an async operation.
- Its states are pending, fulfilled, and rejected.
- Use .then() for success, .catch() for errors, and .finally() for cleanup.
- Advanced Promise methods include all, race, allSettled, and any.
- async/await is the modern readable syntax for handling Promises.
हिंदी सारांश:
Promise async operation ke future result ko represent karta hai. Iski states pending, fulfilled aur rejected hoti hain. Success ke liye then, error ke liye catch, aur cleanup ke liye finally use hota hai. Advanced methods me Promise.all, race, allSettled aur any aate hain. Modern syntax ke liye async/await sabse popular hai.
Frequently Asked Questions
What is a Promise in JavaScript?
A Promise is an object that represents the eventual success or failure of an asynchronous operation.
Why are Promises used in JavaScript?
Promises are used to handle asynchronous code in a cleaner and more manageable way than nested callbacks.
What is the difference between then and catch?
then handles successful results, while catch handles errors or rejected Promises.
What is Promise.all used for?
Promise.all is used to run multiple Promises in parallel and return the results when all of them succeed.
Is async/await better than Promises?
async/await is not different from Promises internally. It is just a cleaner and more readable syntax built on top of Promises.