Home Courses Promise Explain

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

  1. Code runs line by line
  2. 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:

  1. If any operation takes time (API call, complex logic), the whole application waits
  2. The UI becomes slow or unresponsive

Asynchronous Approach

  1. Time-consuming tasks run in the background
  2. Other code continues executing
  3. 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:

  1. new Promise() creates a promise
  2. It takes a callback function
  3. Two parameters:
  4. resolve() for success
  5. reject() 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:

  1. setTimeout uses a fixed delay
  2. 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);
});
}


Share this lesson: