Today I'm going to be writing about Promises in Javascript and I'm going to do my best to keep it as simple as possible.
What is a promise?
A promise is an object which produces a value some time in the future, the value is not available yet but it will be resolved at some point in the future. For example, a promise in Javascript is like a promise in real life. If you say you promise to finish your homework by the end of the day, you either fulfill your promise or you fail. A Promise in javascript does the same thing. Promises can only be made for the future and it has two outcomes, either it is fulfilled or not, and we call these outcomes 'resolve' or 'reject' accordingly.
Even thou there are two outcomes, there are three stages in a promise object.
1. Pending: This is before anything happens, before the promise succeeds or fails.
2. Resolve: This is when the promise has been completed.
3. Rejected: This is when the promise has failed.
Before we move on, there are a couple of other questions we have to answer:
Why do we use promises?
Promises are used to handle asynchronous operations in javascript (I will explain what that means in a moment). Prior to promises we used to use callback functions but this process had limited functionality because it created unmanageable code. People know this unmanageable code as Callback Hell or the Pyramid of Doom which consists of multiple nested callbacks which makes code hard to read and debug. To summarize, promises are a more elegant way to handle asynchronous operations and that's why we use them.
Asynchronous Programing
Asynchronous programing is very relevant to javascript because we are often making requests to servers some place else and it can take some time to get your data back. Asynchronous programming is when something is going on but you don't want to wait until that thing is done to continue your program and you want to continue while is happening. This is when we use promises.
Now let's try to work on setting up a new promise with a simple example:
A new promise takes a callback function and this callback function has two arguments resolve and reject. My promise is going to be finishing my homework to follow my early example:
const homework = new Promise((resolve, reject) => {
}
Now let's put our options with will be if I finish(resolve) or if I don't finish(reject)
const homework = new Promise((resolve, reject) => {
let iDidIt = true;
if(iDidIt){
// if my promise was fulfill
resolve('going to watch tv')
} else {
// if my promise wasn't fulfill
reject('going to fail your class')
}
});
Now we have to execute this promise and we have to wait for it. The way to return a promise is to use the method then()
which tells you that this was a success and you have to chain it to our promise. It will give us an output of 'you are going to watch tv'
const homework = new Promise((resolve, reject) => {
let iDidIt = true;
if(iDidIt){
// if my promise was fulfill
resolve('going to watch tv')
} else {
// if my promise wasn't fulfill
reject('going to fail your class')
}
});
// then the method is fired
homework.then((fromResolve) => {
// return a promise that was fulfilled
console.log(`you are ${fromResolve}`)
});
// 'you are going to watch tv'
Now we need a way to let us know if we got an error and our promise wasn't fulfill. Here is when we use our method catch(). Let's imagine I didn't do my homework and let's chain our catch method. I will change our variable iDidIt to false. Our output will be 'you are going to fail your class'
const homework = new Promise((resolve, reject) => {
let iDidIt = false;
if(iDidIt){
// if my promise was fulfill
resolve('going to watch tv')
} else {
// if my promise wasn't fulfill
reject('going to fail your class')
}
});
// then the method is fired
homework.then((fromResolve) => {
// return a promise that was fulfilled
console.log(`you are ${fromResolve}`)
// catches an error
}).catch((fromReject) => {
console.log(`you are ${fromReject}`)
});
// you are going to fail your class
There you go!
Of course I made a simple representation of how a promise works but a more accurate reason of how to use a promise is
if we request data from an outside source.
When we request data from the server by using a Promise, it will be in pending mode until we receive our data. If we achieve to get the information from the server, the Promise will be resolved successfully but if we don't get the information then the Promise will be in the rejected state.
Conclusion
Promises have many benefits when handling asynchronous operations like improving code readability, better flow and better error handling. You should definitely use them over callbacks.
I hope you enjoyed this blog!
Top comments (0)