Thursday, 6 July 2017

AngularJS Deferred & Promises

When you have started working on AngularJS. You have to deal with the asynchronous call. you must come to know $http and $resource services. These both services are used to get server side data asynchronously. To handle an asynchronous call, you need to define callbacks. Deferred-Promises is a design pattern which helps you to deal with these callbacks.

It is not a problem to work with $http/ $resource. The real problem arise when you have to deal with multiple callbacks which are dependent on each other.

Promise In Angularjs- $q Service

Promises in AngularJS is provided by $q service. $q service is a service that helps you to run your code asynchronously.

Deferred Object: Deferred is an object which exposes the promise. It has  mainly three methods resolve(), reject(), and notify(). Deferred returns promise object. When Deferred completes, You call methods either resolve(), reject(), and notify() . It calls callback register to either resolve(), reject(), or notify() according to how it has completed.


function sayHelloAsync(name) {
    return function () {
        var defer = $q.defer()
        setTimeout(function() {
            //Greet when your name is 'deepak'
            if (name == 'deepak') {
                defer.resolve('Hello, ' + name + '!');
            }
            else {
                defer.reject('Greeting ' + name + ' is not allowed.');
            }
        }, 1000);
        return defer.promise
    }   

Promise Object: A promise is an object which is return by a Deferred object. You can register different callbacks for different events resolve(), reject(), or notify() and it will execute when the async function has completed.


var helloPromise = sayHelloAsync('deepak');
helloPromise.then(function (data) {
    console.log(data);
}, function (error) {
    console.error(data);
})   

Promise API
A new promise is created when you create a defer. You can get the instance of promise object by defer.promise. It is used to getting the result of the defer when a promise has completed. There are three events where you can bind your listeners.

Some other useful features- $q.all()
$q.all() is one of the method that i use more frequently. $q.all accepts array of promises as argument. Once all of the promises get completed. you will get the result in callback function as array of results.


var promise1 = $http({method: 'GET', url: '/api-one-url', cache: 'true'});
var promise2 = $http({method: 'GET', url: '/api-two-url', cache: 'true'});
$q.all([promise1, promise2])
    .then(function(data){
        console.log(data[0], data[1]);
    });

3 comments:

  1. Your explanations of Promise and Deferred In Angularjs are useful for my studies. I am beginner of learning angularjs 2 course.
    .

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hello There,

    Muchas Gracias Mi Amigo! You make learning so effortless. Anyone can follow you and I would not mind following you to the moon coz I know you are like my north star.

    In AngularJs 1, in case of ngRepeat there is syntax called limitTo which basically restrict the for loop for a certain number inspite of main array may contains more than that limitTo value. But in angular 5, limitTo has been dropped in case of ngFor. Then what is the alternative of that ?
    I look forward to see your next updates.


    Thank you,
    Kajal

    ReplyDelete

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)