I promised to continue contributing to open source in my previous post, and I've decided to keep that Promise by writing about a recently learned concept called javascript PROMISE!
So it was a long and stressful day for me, and it was also quite hot outside. I needed a cold drink but couldn't leave what I was doing, so I asked my brother to run the errand of getting a cold drink for me while I continued working. I realized at the end of the day that I had previously practiced the Promise concepts.
The Breakdown of the Errand
This is a breakdown of everything that happened during the errand;
- I called my brother and asked him to assist me in getting the drink.
- I continued working while he ran the errand.
- I was expecting him to either return with a cold drink or not.
- What my reaction is to whatever point 3 above is.
The Errand and JS Promise
The errand is related to how javascript Promise works:
The Creation of the Promise
The first 3 points above will be linked to how Promise works using the block of code below:
const coldDrink = true;
const brother = new Promise((resolve, reject) => {
if (coldDrink) {
const coldDrinkBought = 'I was able to get the cold drink';
resolve(coldDrinkBought);
} else {
const coldDrinkNotBought = 'I was unable to get the cold drink';
reject(coldDrinkNotBought);
}
});
I mentioned that I had to call my brother, which is analogous to creating Promise or promisifying my brother. I created a promise by calling my brother to help me get a cold drink which is shown in this line of code const brother = new Promise((resolve, reject) => {...};
.
I also didn't stop working while my brother ran the errand, explaining Promise's asynchronous nature.
While I was still working, I was anticipating two outcomes from my brother, whether he was able to obtain the drink or not. These two possibilities are handled by the parameters of the function within the Promise, which are resolve (which handles getting the cold drink) and reject (which handles not getting the cold drink).
The consumption of the Promise
This part explains my response to both possibilities of getting the cold drink from my brother.
brother()
.then(iGotTheColdDrink => {
console.log(iGotTheColdDrink);
})
.catch(iDidNotGetTheColdDrink => {
console.log(iDidNotGetTheColdDrink);
});
If my brother had gotten the cold drink, it is resolved from his end, and I can then receive the drink with .then method. If he was unable to obtain the drink, indicating it was rejected, I can obtain my money back from him using the .catch method. At this point, I think I'll have a drink.
Summary
- The .then method handles the result of the Promise's resolve response.
- The .catch method handles the result of the Promise's reject response.
- This is an illustration to explain few of the concepts, to know more, check out node.js official site.
With my illustration, I hope I've fulfilled my Promise of explaining the fundamentals of Promise. Catch you next time (pun intended).
Top comments (0)