Asynchronous call to a REST API using Node.js and using the Promises.

There is nothing new about sending a request to a REST API and fetching a response.

In this blog we will show how can we make an asynchronous call to a API, which means your node.js code will be able to perform other operations while it requests sent to an API fetched the response.

What is a promise?

Promise is an object representing the eventual completion or failure of an asynchronous operation.

A promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

To learn about promises, go to Promises

Here is our example,

Below code is for a REST API call using Node ‘s HTTPs module.

test1.js

module.exports = {
  httpGet: () => {
    var https = require('https');
    return new Promise((resolve, reject) => {
      https.get('https://jsonplaceholder.typicode.com/posts/1', function (res) {    
        res.on('data', function (data) {
         var body += data;
        });
        res.on('end', function () {
          var response = JSON.parse(body);
         
          resolve(response.title);
        });
        res.on('error', (err) => {
          reject(err);
        })
      });
    });
  }
}

 

test2.js

 

var test1 = require('./test1.s');
test1.httpGet()
  .then(response => {
    console.log('Title from Response-->', response);
  }).catch(err => {
    console.error('error', err);
  });
console.log("I am executed first");

Here is our output:

Screenshot (40)

As you can see, it first prints “I am executed first” and then the response form the API.

Advertisements

2 thoughts on “Asynchronous call to a REST API using Node.js and using the Promises.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s