Start Working with Promises in Node.js

    Apr 20, 2017       by Pankaj Kumar
promise.jpg

Hello Everyone, Today we will create demo on use of promises in nodejs application. As we all know in the current time complex apps are getting created. And to manage complexity within the app one need to use the right tools. Since Nodejs is asynchronous by nature, But the same feature becomes hactic to handle the data flow within the code. Promise is also a very useful library to overcome the complexity of Asynchronous Javascript code.  At some places in our code we need the data first then to proceed further so at these situation need of promise comes.

What is a Promise?

The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:

  • pending - The initial state of a promise.
  • fulfilled - The state of a promise representing a successful operation.
  • rejected - The state of a promise representing a failed operation.

Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).

nodejs promises

 

As we can see in the above picture, the basic steps to create promise.

Creating a Promise

var newPromise = new Promise(function(resolve, reject){
   ....
})

 

newPromise is a Promise type object which allows us to use it for later.

Now we will create a demo of using promises in nodejs application. So here we will  use Github REST  API to fetch fetch the details about UsersRepositories etc. 

 

Let's have a look over the code 



 
let request = require("request");
let userDetails;
 
function initialize() {
// Setting URL and headers for request
var options = {
url: 'https://api.github.com/users/pankajkrr',
headers: {
'User-Agent': 'request'
}
};
// Return new promise
return new Promise(function(resolve, reject) {
    // Do async job
request.get(options, function(err, resp, body) {
if (err) {
reject(err);
} else {
resolve(JSON.parse(body));
}
})
})
 
}
 
function fetchData() {
var initializePromise = initialize();
initializePromise.then(function(result) {
userDetails = result;
// Use user details from here
console.log(userDetails)
}, function(err) {
console.log(err);
})
}
 
fetchData();
 

 

Let's discuss code, At the top we have declared a variable userDetails. Our purpose is to fetch  details of a Github user from Github and load that variable. At the top we have create a method initialize within which we have created our promise and after calling github API. Then we are calling resolve method to pass data back to the handler which implements then on the promise.

 

We have console the data we are getting from promise. Have a look what we will get in console.

Now we have another method at the bottom named fetchData where we get the Promise from above function and attach a function callback in the then function.

 

{
  "login": "pankajkrr",
  "id": 9263354,
  "node_id": "MDQ6VXNlcjkyNjMzNTQ=",
  "avatar_url": "https://avatars0.githubusercontent.com/u/9263354?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/pankajkrr",
  "html_url": "https://github.com/pankajkrr",
  "followers_url": "https://api.github.com/users/pankajkrr/followers",
  "following_url": "https://api.github.com/users/pankajkrr/following{/other_user}",
  "gists_url": "https://api.github.com/users/pankajkrr/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/pankajkrr/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/pankajkrr/subscriptions",
  "organizations_url": "https://api.github.com/users/pankajkrr/orgs",
  "repos_url": "https://api.github.com/users/pankajkrr/repos",
  "events_url": "https://api.github.com/users/pankajkrr/events{/privacy}",
  "received_events_url": "https://api.github.com/users/pankajkrr/received_events",
  "type": "User",
  "site_admin": false,
  "name": "pankajit",
  "company": null,
  "blog": "",
  "location": "new delhi",
  "email": null,
  "hireable": true,
  "bio": null,
  "public_repos": 3,
  "public_gists": 0,
  "followers": 0,
  "following": 0,
  "created_at": "2014-10-16T07:01:29Z",
  "updated_at": "2018-09-20T11:06:58Z"
}

 

Pretty cool! Finally, our task completes here.

That’s all for now. Thank you for reading and I hope this post will be very helpful for start using promise in nodejs app.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


Find other similar Articles here:

Other Articles