A Promise represents the state of an asynchronous operation. This asynchronous operation can be anything i.e fetching data from an API, reading contents from a file, etc.
Before promises we had callbacks, but they had fewer capabilities and lead to a sloppy code. When dealing with multiple callbacks, our code will become a callback hell which becomes difficult to manage.
A Javascript Promise consists of four states:
- Fulfilled: The operation was completed successfully.
- Pending: The operation isn't completed, it's still in process.
- Rejected: The operation is failed.
- Settled: The operation is either fulfilled or rejected.
A promise can be created by using
Promise
constructor.
const isNumEven = (num) => new Promise((resolve, reject)=> {
if(num % 2 === 0) {
resolve(true)
} else {
reject(false)
}
})
Now the above-created promise can be used as
isNumEven(5)
.then(res => console.log(res))
.catch(err => console.log(err))
The then
handler is invoked when the promise is fulfilled while the catch
handler is invoked when the promise is rejected.
Here in this case the catch
handler is invoked as the number we have passed to the function is not even.
Chaining Promises
When the result of a promise is another promise, we have to chain them to get the results.
isNumPrime(5)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
This method of handling asynchronous operations looks fine when we have 2 to 3 promises but it gets unmanageable when there are more than that. Then async await
comes into the picture. They help you to handle multiple promises very easily.
That's it for now. Thanks for making it to the last. Let me know any feedback or suggestions you have for this article. Also, let me know if you want me to write on async await
.
Top comments (4)
Simplest explanation for javascript promises. Thanks for sharing.
Nice explanation 👍
Agree, well explained. You should definitely attempt with async await
Here it is: dev.to/deepansh946/async-await-in-...