Promise Object
- Promise is an object that holds an eventual result of an asynchronous operation.
- Promises used to avoid nested callbacks (Callback Hell).
- It makes readablilty and debuging easy.
Promise is like a promise statement made to a person that someone will fulfill what they have promised
const result = new Promise((resolve, reject) => {
// async work happens here
});
Promise has three states
- Pending (Initial Stage)
- Fulfilled
- Rejected
Pending (Initial Stage)
It is the initial stage indicating that the operation is being done.
Fulfilled:
It represents the success of the operation.
Rejected:
It indicates the error in the input or gives the failure output.
Example
if (age >= 18) {
resolve("You are eligible to vote"); // Fulfilled path
} else {
reject("You are not eligible to vote"); // Rejected path
}
<!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>
<h1> Promises</h1>
<p id="para"> </p>
<p id="error" style="color: red;"></p>
<script>
const result = new Promise ((resolve, reject) => {
const age = 28;
setTimeout (() => {
if (age >= 18) {
resolve ("You are eligible to vote");
} else {
reject ("You are not eligible to vote");
}
},2000 )
} )
.then((data) => {
console.log(data);
document.getElementById("para").textContent = data;
})
.catch ( (error) => {
console.error(error);
document.getElementById("error").textContent = error;
} );
</script>
</body>
</html>
- The promise takes a function called executor. It runs immediately once the promise created.This executor receives two functions, resolve and reject.
resolve() and reject()
- resolve(value) — marks the Promise as fulfilled, and value gets passed to .then().
- reject(reason) — marks the Promise as rejected, and reason gets passed to .catch().
.then() and .catch()
Once a Promise settles, you get the outcome:
- .then(callback) — runs if the Promise resolved; callback receives the resolved value.
- .catch(callback) — runs if the Promise rejected; callback receives the rejection reason.
Promise chaining
.then() and .catch() are methods called on the Promise object, and each returns a new Promise, so you can chain more .then()s after it if needed.
Top comments (0)