ES6 Promises with Nodejs

Hey guys, Hope you are doing well. I got a request to wrote a blog about ES6 promises. So here it is.

Promises Promises?

JavaScript Promises are not as difficult as people think it is. Yes it can be confusing at times. but once you get the hang of it you will love. They are impressive alternative for callbacks. Before Es6/Es2015 we had to use third party libraries for promises like Bluebird and Q. But now ES6 comes with its own native Promises.

What are Promises?

So what are promises? Well consider that you Promise to meetup with your friends. but you don’t know if you would actually be there. anything can happen your car’s tire gets busted, you get sick etc etc. That’s whats JavaScript Promises are.

They have 3 states :

  1. Pending State : You promised your friends to meet and planned to but its hasn’t been fulfilled or canceled yet.
  2. Resolve State : You reached and met with your friends hence promise fulfilled.
  3. Rejected State : You canceled the plan because something came up. Hence promise was not fulfilled.

 

Why Promises and Why not Callbacks ?

Well If you have been around for a while and worked on JS you probably have heard of the term “CallBack Hell“. Making multiple asynchronous calls one after another creates a callback hell and it looks kinda like this.

It makes your code messy and less readable. And here is an example for making multiple asynchronous via promises.

The above examples were if you want to make multiple async calls one after another. Now i will show you what it’s like if you make parallel calls using callbacks and promises.

Now the Promise version

Promise.all method takes an array of Promises and returns an array of output in the then method. and if there are any rejections you can catch it in catch method.

How to make Promises ?

Ok so now that we understood why we want to use promises. lets jump into how to create a promise function and then consume it.

So we created a function that returns a promise. The Promise constructor takes a function as its parameter which takes resolve and reject as its own parameters. You make your async call in the function in this call we are using request module to hit a get request on a url. If the request is result in an error we will reject the Promise. if the request is successful we will resolve it.

Now that we have created a Promise lets consume it in a node.js routes.

 

And that’s how we can consume the JavaScript Promises.  That’s all you need to know to get started with Promises.

I have uploaded the full project on my github account you can clone it or download it from here. Until next time. Have a Good day or Night 😀

1 thought on “ES6 Promises with Nodejs

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.