Javascript promises

Most of the processes in javascript are asynchronous–meaning they are handled independently from the main program and run in background. If you have coded an AJAX call, probably have used promises as well.

Promises–an object acts as proxy to the results that is initially unknown due to computation of its value. And value computed by promises are called future also known as resolving, fulfilling or binding. Promises are the best way to handle asynchronous programming flow and other convoluted flow.

Most of the javascript libraries developed recently used promises under the hood. One of them is AngularJS. And for the same reason i am using AngularJS in code examples.

    var project = angular.module('project', []);
    project.controller('app', function($scope, $http){
        var url = 'http://api.openweathermap.org/data/2.5/weather'
        var params = {
            'q': 'singapore', 
            'appid': '82951579ce682b34fdd35031ccc02f39'
        };

        var ajaxPromise = $http.get(url, params);
        ajaxPromise.then(function(response){
            $scope.weather = response.data.weather;
        });
    });

In the example above, calling $http.get(url) returns a promise which is stored in a variable ajaxPromise. Method then can be used to render the response data.

Promise has three states.

Once a promise is done either fulfilled or rejected. It is immutable–means it can never change again. Promises can only have two possible outcomes: success and failure. And this is how a promise object is created:

    var promise_object = new Promise(function(success, failure));

Let’s extend our first example and add failure scenario in it:

        var ajaxPromise = $http.get(url);
        ajaxPromise.then(function(response){
            $scope.weather = response.data.weather;
        }, function(error){
            $scope.error = 'weather data can not be loaded!'
        });

Promises .then methods takes two arguments as callback to handle resolve and reject states respectively. Thus it can be use for success or for both success and failure. Use .catch method to handle reject or failure only.

        var ajaxPromise = $http.get(url);
        ajaxPromise.then(function(response){
            $scope.weather = response.data.weather;
        }).catch(function(error){
            $scope.error = 'weather data can not be loaded!'
        });

Above i tried to explain very basic of javascript promises and how they can be used to improved code quality and its outcome. But they are very efficient in asynchronous programming model.

 
0
Kudos
 
0
Kudos

Now read this

Python Generators: yield

In this post i will try to explain the basics of python generator. And will be writing another post to cover advance use and some debugging techniques. In python, generator is part of functional programming. A generator is an object that... Continue →