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?
A
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:
As you can see, it first prints “I am executed first” and then the response form the API.
2 thoughts on “Asynchronous call to a REST API using Node.js and using the Promises.”