What is Promise?
In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that is not yet known but will be available at some point in the future. Promises provide a structured and cleaner way to handle asynchronous code compared to traditional callback functions, which can lead to "callback hell" in complex scenarios.
A Promise can exist in one of three states:
Pending: The initial state.
Fulfilled (or Resolved): The operation completed successfully.
Rejected: The operation failed.
Creating a Promise:
A new Promise
is created using the Promise constructor. This executor function receives two arguments: resolve
andreject
.
Handling Results:
.then():
Used to attach callbacks for when the Promise is fulfilled.
.catch():
Used specifically to handle errors (rejections) in a Promise chain.
syntax:
const login=new promise((resolve,reject)=>{
let password=true;
if(Password){
resolve();
}else{
reject();
}
})
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function login(){
return new Promise((resolve,reject)=>{
let password=true;
if(password){
resolve();
}else{
reject();
}
})
}
login()
.then(()=> console.log("Successfully login..."))
.catch(()=>console.log("invalid password..."))
</script>
</body>
</html>