Promise in JavaScript | Part 2: Creating a Promise

Understanding JavaScript();

Madhav Mansuriya
6 min readJan 8, 2023

--

This is part 2 of promises in JavaScript, this story covers the creation of promises, chaining of promises, handling errors and a few other useful methods of promise.

What? you haven’t read part 1 yet, read it here. Part 1 talks about what is a promise, some benefits and how and where it is used. It's just a 7 min read.

Creating a Promise

  • To create a promise in JavaScript we need to use the new keyword and a Promise constructor.
Creating a promise
  • Promise constructor takes a callback function and has two methods as params, resolve and reject.
  • this is because a promise can only have two states, either the promise will be resolved or it will be rejected.
  • assume we are fetching userData from an API, mimicking it and adding a dummy object.
  • if your fetch operation was successful, we can use the resolve() method to resolve the promise, resolve will take the data as a param that we want to return from the promise, for example: resolve(userData).
  • if your fetch operation has some issue and the data is not fetched for some reason we can use the reject() method to return the error, it's called rejecting a promise, for example: reject(error).
  • In the end, we need to return a promise to the consumers.

Consuming a promise

consuming a promise
the output of the consumed promise
  • we can consume any promise using .then() method provided by Promise API in JavaScript, read more about consuming a promise here.

Promise Chaining

  • we already have seen the chaining of the promise in the previous story, just recalling.
  • continuing the same example of fetching users, fetching user friends based on user, and sending a gift to user friends.
creation of promise
chaining promises
  • you might be saying “this is cheating boiee, you only said without a return statement promise chain won’t get executed further, and now you are not writing any return statement”.
  • no, my friend, I am not lying or not doing cheating with you, this code is just written in an ES6 format, where you don’t need to use a return statement if you are writing your code in a single line, it will automatically handle it. Read more about ES6 here.
  • first we need to fetch the user using fetchUser(), which returns a promise and based on the user we need to fetch the friends of the user using fetchUserFriends() for this we need to chain the promises using .then() method of promise API.
  • once the user friends are fetched we need to send the gifts to those friends, we will be using the same .then() method to chain the promise and complete the operation.
  • you might be wondering what if something breaks in between.

This is my code it never breaks 😒 don’t you trust me 😏. Relax just kidding 😅 😆 even google code breaks who the hell am I to be such confident?

Error handling in Promise

  • what if some promises are rejected? what will be the effect?
  • let's say sending gifts Promise sends a rejection because of some internal failure. (not getting resolved, executing reject part)
promise rejected (unhandled).
  • It will throw some error like this, it says “Uncaught (in promise) Error sending gifts”.
  • it says it is Uncaught, it will fail in the user console, and the user will not see anything on the page if the loading of the page or some portion of the page is dependent on this promise, because the promise is not handled properly.
  • using .then() we have taken care of the good parts(consuming the promise) but we forgot to handle the bad part.
  • we can use .catch() method provided by the promise API to handle/catch the errors/rejections that might occur in the promise.
using .catch()
promise rejected (handled)
  • if the errors/rejections are handled properly we can easily show the error on the page that the gifts are not been sent to your friends or whatever. (I don’t have such friends who send me gifts 😞 if you wish you can 😬)
  • wait wait wait, I’ve got an interesting thing to share with you about .catch() I bet you might have heard of but never used the .catch() in this way.
  • we can use .catch() at any level of consuming promise in the promise chain, yes you heard it right, we can use .catch() after the first chaining or the second chaining or at both places, it's completely your wish.
using .catch() at the first level of chaining
  • we are handling the rejection of fetchUserFriends() promise at the next level of chaining after consuming it.
  • if the fetchUserFriends() promise fails the sendGift() promise will still get consumed and executed, no matter if user friends are fetched or not.
  • ya ya, you might be thinking about whom these gifts will be sent to if the user friends are not fetched. Is he gone mad or what?
  • We generally don’t use .catch() in this way, this example was just to explain the concept. As a developer, it's your responsibility to use .catch() in the correct place.

.finally()

  • there is one more method named .finally() provided by promise API in JavaScript
  • as the name suggests it is called at the end “finally, finally is getting called 😅” ya ya I know it was a lame one, but please bear with me.
  • this .finally() method is used at the end of promise chaining, it's like a wrap-up method.
  • for example, after performing any operation like fetching a user, fetching user friends and sending gifts to them, as a good practice we need to close the DB connection.
  • DB connection should be closed no matter if all promises are resolved or if any of them are rejected, so you can close the DB connection in the finally() block.
  • you can compare it with a garbage collection mechanism in any programming language, after the completion of any task or operation garbage collection comes into play.
using .finally()
  • the output of .finally() when all promises are resolved.
output of .finally()
  • the output of .finally() when any of the promises is rejected.
  • the .finally() output is getting printed at the end, no matter if all promises are resolved or rejected.

one can not focus for this long, but you are awesome 😎, if I will try to explain some more topics in the same story you will get bored.

so ya that’s it for this story, meet you in the next story on “some useful promise methods | the last part” 😎 after this line I am feeling like a director of the film “the last part 😅”

stay tuned for the last chapter of promise, and grab a coffee ☕️ until then.

what? you wanna send me a gift 🎁 😃 please don’t hesitate, but before that get your hands dirty with practising the above concepts.

--

--

Madhav Mansuriya
Madhav Mansuriya

No responses yet