Node JS – REST calls with ES6 Promises + Co JS Module

Here is an example of factory that creates an httpService to communicate with an external API with REST. We are using the npm module “request” to perform the HTTP calls. We are using as well ECMAScript 6 classes and promises, as long as the npm module “co”, that allows us to take advantage on the ES6 generators to await for async elaborations that returns a promise.

"use strict";

var request = require("request-promise");
var co = require("co");

class HttpService {
     constructor(baseUri) {
          this.baseUri = baseUri;

     call(options) {
          var self = this;

          console.log("Calling", self.baseUri + options.uri + "..");

          return new Promise(function (resolve, reject) {
               co(function* () {
                    try {
                         var data = yield request({
                              uri: self.baseUri + options.uri,
                              method: options.method,
                              headers: options.headers,
                              form: options.postData,
                              json: true
                    } catch (err) {
                         if ( == "StatusCodeError") {
                              console.log("ERROR: returned status code was", err.message);
                         } else {
                              console.log("ERROR:", err.message);

module.exports = {
     make: function (baseUri) {
          return new HttpService(baseUri);

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s