Promises In Javascript
Poornima Gowda
Posted on August 20, 2024
In javascript, promises are one of the techniques to deal with asynchronous operations that introduced in the ES6. If you are working on like fetching data or waiting for timer using setTimeout method, much easier to manage and more readable.
What is Promises?
A promise is an object that represents the eventual completion/ failure of an asynchronous operation and its resulting value. it can be in one of three states.
1.Pending: The initial state, Operation is ongoing, neither
fulfilled nor rejected.
2.Fulfilled: The operation completed successfully.
3.Rejected: The operation failed.
Syntax
const myPromise = new Promise((resolve, reject) => {})
Firstly, we have to use a constructor to create a Promise object by using new Promise(),This is called executor. It takes a single function with two parameters: resolve() and reject().
And resolve is executed when the operation is successful. Otherwise, reject is executed when operation fails.
Consuming process:
So, we can't access promises directly, to handle the promise result we have to use .then() & .catch() method
myPromise.then(() => {
//console here..
}).catch(() =>{
//error
})
.then() - It is used to handle the result of a Promise once it has been resolved (successfully completed) or rejected (failed).
.catch() - This method is invoked when promise is rejected or some error has occurred in execution. This method is used for handling errors.
Posted on August 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.