Angular.js Promises – Deferred and Promise handling

A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.

Promises are highly useful when you wish to synchronize multiple asynchronous functions and also want to avoid Javascript callback hell. as following is a asynchronous example.

step1(function (value1) {
 step2(value1, function(value2) {
 step3(value2, function(value3) {
 // do something.
 });
 });
});

and alternative use of promise library for above example is:

Q.fcall(promise1)
.then(promise2)
.then(promise3) {
 // Do something
})
.catch(function (error) {
 // Handle any error from all above steps
})
.done();

Angular.js provide a service $q with implementation of promises/deferred objects inspired by Kris Kowal’s Q.  you can simply start using it as a service.

angular.module('PromiseExample').controller('PromiseCtrl', ['$scope', $http, $q, function ($scope, $http, $q) {
 
 function getUser(){
   var deferred = $q.defer();
   $http.get(ApiUrl+ '/user/' + $scope.uuid)
   .success(function(result){
    deferred.resolve(result);
   })
   .error(function(error){
     deferred.reject(error);
   });
 
   return deferred.promise;
 }

 getUser().then(function(user){
   $scope.user = user;
 });

}]);

In above code, getUser() is creating a $q.defer() object which has returned a promise at the end of function, we have called it remote object earlier above. now deffered.resolve provide us the results in case of success and deffered.reject object gonna tell us the reason why it failed.

$q.defer() also have a method notify() which gives the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.

You can also wrap multiple promises using $q.all. all function combines multiple promises into a single promise and later on you can foreach through responses.

var first = $http.get("/api/v1/user/educations/"+user_id),
second = $http.get("/api/v1/user/employments/"+user_id),
third = $http.get("/api/v1/user/posts/"+user_id);

$q.all([first, second, third]).then(function(result) {
// foearch through all responses.
angular.forEach(result, function(response) {
console.log(response.data);
});
});

If you want to take look at further examples of Promises, you can see it Kris Kowal’s Q and Angular $q service

Introduction to WebSockets – Server, Client examples using Node.js

Initially the paradigm about web was Client/Server model, in which clients job is to request data from a server, and a servers job is to fulfill those requests. This paradigm fulfills the web requirement for number of years, but later on with Introduction of AJAX makes us enable to communicate with server asynchronously.

Now using AJAX it was easy to communicate with server but we still need more power when talk in term of real time applications. an simple example http request could be like bellow.

GET /users/ HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120
Pragma: no-cache
Cache-Control: no-cache
So every time you make an HTTP request a bunch of headers and cookie data are transferred to the server and in response you will response header along with data. If you are working on a real time application or game running in browser, you will have problems running things smoothly because every request contain a lot of unnecessary data which is not needed every time you make request to server. so here comes WebSockets which is a way of creating a persistent, low latency connection that can support transactions initiated by either the client or server.
Using WebSockets you can start a bidirectional connection where client/server can use to start send data at any time. Client establishes connection through a process called WebSocket handshake, client will send regular HTTP request to the server – upgrade header is included in this request to let server know that a client want to establish a WebSocket connection.
GET /chat HTTP/1.1
Host: example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Now if the server supports the WebSocket protocol, it will send upgrade header back in the response.

TTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After handshake is complete the initial HTTP connection is replaced by a WebSocket connection that uses TCP/IP connection and now either party can starting sending data.

A simple client side connection is like bellow.

var socket = new WebSocket('ws://example.com');
// onopen send/recieve data
socket.onopen = function(event) {
console.log("connected to server.")
};
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};

To send a message through the WebSocket connection you call the send() method. You can send both text and binary data through a WebSocket.

Now if you want to create a simple socket server using Express.js and Socket.IO.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

Server is now listening at port 3000, which can recieve and send data.

Express.Js Middleware, What is next()?

You may have noticed use of next() function while looking at node.js code.

Express is a routing web framework which utilize essentially a series of middleware calls. piece of code for a simple route could be like bellow.

app.get('/users/:id', function(req, res) {
 // logic to fetch user for provided id.
});

and with a additional parameter next

app.get('/users/:id', function(req, res) {
 var user_id = req.params.id;
 if(user_id) {
 // do something
 } else {
 next(); // here comes middleware.
 }
});

So what is next() doing here. In the example, for instance, you might look up the user in the database against provided user_id but if user not found in database, It passes control to the next matching route. It is a more flexible and powerful tool that could sit between/before the routes and can perform specific tasks for you.

Let say you want to perform check if user is authenticated  and have a started session with app, It is much easy to deal with that using middleware instead of specifically check at each route.

app.user(function(req, res, next) {

if (req.session.auth) {
next();
} else {
res.redirect("/auth");
}
});

It will check session before each route as long as we put this code before our routes. Express will run middleware in the order added to the stack. The router is one of these middleware functions. As long as you get your above function into the stack before the router, it will be used by all routes and things will work.

There is list of common actions you can perform using middleware. such as logger, bodyParser, cookieParser, errorHandler etc.

Web development is war of tools these days!

Today development is war of tools. more better tools lead to faster turn around. a better tool could help you to achieve the same task in few minutes which you are expected to finish in hours.

I can give you idea of many tools in this article which really makes life easy. during development you will find a wide range of tools which are actually more powerful than we think at first. exploring the features of that tool is the key, then keep yourself upgrade with new features and upgrades

If i am talking about tools for development, i will include everything which is meaningful while i am sitting at my desk. that could be anything – form a browser extension to IDE’s(code editors).

An IDE which consists of a source code editor, automation tools, Snippets support, debugger and a better auto-complete system for supported languages could lead to fast development compare to a one which lacks these features. I strongly believe opensource IDE’s are more powerful these days. Best example is Brackets is more efficient for any kind of development than Dreamweaver, both are made by same vendor. but opensource community could boost product development. I have found a amount of extensions for brackets (which can be installed using extension manager) can do many tasks more easily without leaving even leaving interface. i could not these things expect from Dreamweaver in next couple of releases.

Another example is Sublime text which another hero in world of IDE’s. i find it more faster and lightweight than any other code editor.

There are other tools like Navicat which is well-designed Graphical User Interface for database management and development software, it includes support for MySQL, MariaDB, SQL Server, Oracle, SQLite and/or PostgreSQL. i handles connections and session very smoothly, you don’t need to always open phpmyadmin always. there are others sqlyog etc.

Here i can talk about couple of Firefox/chrome extensions which provide enhanced features and are helpful during development. you need to explore development tags for these browser while searching.

Here i didn’t mentioned any tools/frameworks which we used during development like bootstrap, JavaScript libraries etc and a long list.