Promise Explain
What is a Promise?
A Promise is used to handle asynchronous operations in JavaScript.
It gives a guarantee:
“When the task completes (success or failure), it will return a result.”
Why Promises are Needed?
Synchronous JavaScript
- Code runs line by line
- Each line waits for the previous one
let a = 10;
let b = 20;
let c = 30;
let d = a + b + c;
console.log(d); // 60
Problem:
- If any operation takes time (API call, complex logic), the whole application waits
- The UI becomes slow or unresponsive
Asynchronous Approach
- Time-consuming tasks run in the background
- Other code continues executing
- When the result is ready, the Promise returns it
Creating a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Code Executed");
}, 2000);
});
Key Points:
new Promise()creates a promise- It takes a callback function
- Two parameters:
resolve()for successreject()for failure
Consuming a Promise (.then)
promise.then((result) => {
console.log(result);
});
Output after 2 seconds:
Code Executed
Why not use setTimeout directly?
setTimeout(() => {
console.log("Code Executed");
}, 2000);
Difference:
setTimeoutuses a fixed delay- Promise returns the result whenever the task actually completes
Real Example – Login System
HTML Button
<button onclick="handleLogin()">Login</button>
userLogin() Function
function userLogin(){
let email="anil@test.com";
let password="1234567890";
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve({login:true,id:100});
}, 3000);
});
}
userToken() Function
function userToken(){
return new Promise((resolve, reject)=>{
setTimeout(() => {
reject({token:"$%#$%%$%$$"});
}, 5000);
});
}