blog.pleb.in

Life of Apps

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Classy Promises with Arrows in Scope - Quick look at some ES6 features

Having seen some code with arrow functions all over and unable to understand it, I decided to spend some time and learn the new features in ES6. I attended Udacity's ES6 course, which had lots of examples and was helpful. Apart from arrow functions, the other features that I was keen on learning were variable scoping with const and let keywords, classes and promises. Here is a quick look at what I learnt.

Arrow Functions
My requirement was only to understand how to read code written with arrow functions as there were quite a few examples using them. Suffice to say, (parameters) => { statements }.

In the code snippet below, where I am using only a single line function, there is no need to encapsulate the code with curly braces. JavaScript: Arrow Functions for Beginners is a good article that describes the arrow functions well.


const and let
The const keyword fixes the value of the variable to what is assigned during declaration. This is useful when importing (requiring) libraries as they do not change in the course of the program. In the code snippet below, variables express and app are declared with const as their values do not change in this course of the program.


When a variable is defined with let, it makes the variable local to the block in which it is defined. In the code snippet above, isError's scope is limited to inside the getCustomer promise block only.

Classes
Coming from a Java background, I wanted to see ES6 classes more out of curiosity than anything else. Not being an expert in JavaScript ES5 helped here as it was easy to relate to Java classes (I did not have to relate it prototypes etc.). In the code snippet below, I create a customer class with attributes for id, name, level and since.


Promises
Finally, promises. I learnt promises from the ES6 Udacity course that I mentioned above and also looking at this useful article on scotch.io. A quick summary is in order. Promises are for best suited for avoidance of "pyramid of doom" that happens when you execute code with callbacks. In promises, there are four states:
  • success: resolved/fulfilled
  • failure: rejected
  • pending
  • complete

Creating promises
In the code creating the Promise, success is notified through a resolve function call and failure is notified through a reject function call. In the getCustomer promise below, I return an error through the reject function call if the variable isError is true. I return customer records for the success criteria through the resolve function.


Calling promises
In the arrow function code where the promise is invoked, the then method notifies us if the method executed successfully or failed. It also has a chained catch method that catches the exception/error. If we set isError to true in the code and return an error, the catch method will get executed.   




Node.js Utility Modules & Configuration

As I learn and understand Node.js better, I try to organize the code better. Some of the changes that I did to the code that does microservices orchestration are:

  • Organized helper code for RabbitMQ and HTTP methods into a separate module by following this useful article
  • Moved the URL details for RabbitMQ to a separate js file following this stackoverflow response
  • Closed RabbitMQ connections on process exit trapping kill & Ctrl-C signals using the morbidly titled npm module called death   

Building Bots with Bottr

It has been a while since I posted to this blog. What have I been up to? I have been looking at some chatbot frameworks, Bottr being one of them. Bottr is a simple JavaScript framework that allows you to quickly build a chatbot. It runs on node.js and can be tested on your local desktop.

Bottr is available as a npm module. After installing the module, you can use it like so

var Bottr = require('bottr');
var BottrApp = require('bottr-app');
var bot = new Bottr.Bot();
//BottrApp for local server
bot.use(new BottrApp());

It has functions to listen to messages received and do some processing. The function below will fire on each message and when done with processing, will invoke the next function using the next() function.

bot.on('message_received', function(message, session, next) {
  //function code here
  //invoke other handlers to process the message
  next();
}

It also has functions that can listen to specific message types/patterns and respond. The function below listens to all messages and echoes them back using the send function. The listen function at the end starts the bot to listen.

bot.hears([/.+/], function(message, session) {
      // Echo the user's message 
      session.send(message.text)
});
bot.listen();

The framework's documentation provides clear instructions on deploying the code in Heroku and integrating with Facebook Messenger. Within a matter of minutes, I was available to deploy the code and use it in Facebook Messenger. However, as the framework is relatively new, the documentation is not exhaustive. This makes it a bit tough to use the framework for building complex bots. As the framework gains popularity and more people start using it, hopefully the documentation will also mature. And we can see more bots built using Bottr.