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

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives