Promises in JavaScript | Promises in JavaScript are a powerful way to handle asynchronous operations.
Promises in JavaScript are a powerful way to handle asynchronous operations. They represent a value that may be available now, or in the future, or never. Promises provide a cleaner and more intuitive way to work with asynchronous code compared to traditional callback-based approaches.
Basics of Promises
A Promise object represents an asynchronous operation's eventual completion (or failure) and its resulting value.
Promises can be in one of three states:
- Pending: The initial state. Neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Creating a Promise:
You create a new Promise using the Promise
constructor, which takes a function (called the executor function) that has two parameters: resolve
and reject
.
//Promises in JavaScript - Promises in JavaScript are a powerful way to handle asynchronous operations.
//Promises can be in one of three states:
//Pending: The initial state. Neither fulfilled nor rejected.
//Fulfilled: The operation completed successfully.
//Rejected: The operation failed.
var promise = new Promise(function(resolve, reject){
var isSuccess =false;
if(isSuccess){
setTimeout((res)=>{
resolve("This is resolved");
});
}
else{
reject("This is rejected");
}
});
promise.then((result)=>{
console.log(result);// Operation was successful!
})
.catch((error) =>{
console.error(error); // Operation was failed!
})
.finally((finally)=>{
console.log('finally called');
//Finally called every time code is executed successfully or failed!
});