A Promise is an object that represents the future result of an asynchronous operation.
Example: API call, file reading, database query.
Promise states -
1. Pending → still waiting
2. Fulfilled → completed successfully
3. Rejected → failed
Example:
const promise = new Promise((resolve, reject) => {
let success = true;
if(success){
resolve("Task completed");
} else {
reject("Task failed");
}
});
Here:
-
resolve()→ marks promise as fulfilled -
reject()→ marks promise as rejectedTo handle the result:
promise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});-
.then()→ runs if success -
.catch()→ runs if error
-
No comments:
Post a Comment