what is promise in javascript?
In JavaScript, a Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value. It provides a structured way to handle asynchronous code, making it more manageable and readable than traditional callback-based approaches.
Basic Syntax:
const login =new promise((resolve,reject)=>{
let pass=true;
if(pass)
{
resolve();
}
else{
reject();
}
})
States of a Promise:
- Pending – Initial state, neither fulfilled nor rejected.
- Fulfilled – 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.
resolve(value) — called when the operation succeeds
reject(error) — called when it fails
Once you call either resolve or reject, the promise becomes settled (fulfilled or rejected) and cannot change.
Example:
<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>
Top comments (0)