Promise In AngularJS

Introduction

Promise is like giving some work to someone and he promises you that the work will be complete. Now until the work is done you can prepare yourself for three situations i.e. he'll do it in a perfect manner, he'll do it but it will not be useful for you, and lastly he has not done it due to some reason.

I have created a sample application to explain it.

Step 1

Firstly, I added a HTML page which will be used to call the controller, and show the custom output.

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5.     <script src="angular.js"></script>  
  6.     <script src="AngularScript.js"></script>  
  7. </head>  
  8. <body ng-app="angularApp">  
  9.     <form ng-controller="angularController">  
  10.         <h2><label ng-bind="Member"></label></h2>  
  11.     </form>  
  12.   
  13. </body>  
  14. </html>  

Here, I created a h2 tag which will show the result coming due to response from promise.

Step 2

After creating the HTML, I worked on the Angular part and for this I created a separate JavaScript file.

  1. var angularApp = angular.module('angularApp', []);  
  2. angularApp.controller('angularController'function ($scope, angularFactory) {  
  3.     angularFactory.checkValues().then(function (data) {  
  4.         var UserType = JSON.parse(data.d);  
  5.         if (UserType.Name == "Anubhav") {  
  6.             $scope.Member = "You are Admin";  
  7.         }  
  8.         else {  
  9.             $scope.Member = "You are not Admin";  
  10.         }  
  11.     }, function (error) {  
  12.     });  
  13.   
  14. });  
  15. angularApp.factory('angularFactory'function ($http, $q) {  
  16.     return {  
  17.         checkValues: function () {  
  18.             dataArr = [];  
  19.             dataArr.push(new Object());  
  20.             dataArr[0]["Name"] = "Anubhav";  
  21.             return $http({  
  22.                 url: 'WebService1.asmx/Save_Session',  
  23.                 dataType: 'json',  
  24.                 method: 'POST',  
  25.                 data: "{'aray':" + JSON.stringify(dataArr) + "}",  
  26.                 headers: {  
  27.                     "Content-Type""application/json"  
  28.                 }  
  29.             }).then(function (resp) {  
  30.                 if (typeof resp.data === 'object') {  
  31.                     return resp.data;  
  32.                 } else {  
  33.                     return $q.reject(response.data);  
  34.                 }  
  35.             }, function (err) {  
  36.                 return $q.reject(err.data);  
  37.             });  
  38.         }  
  39.     }  
  40. });  

Here, firstly I created a module and name it "angularApp".

After this I created a controller "angularController" in which factory method is called. Here you can see that I have used ".then;" it works only when our factory method returns something. Inside that first function is the success function and the second one is error function.

After Controller, I created factory where I made a HTTP POST call to WebService Method, I passed some dummy data in an object. Here also you can see that I have used ".then" which clearly means that functions inside "then" will only execute when something is returned from WebService, if object is returned then it is passed to controller, otherwise deferred state is rejected.

Step 3

At the end I created a WebMethod in WebService.

  1. [WebMethod]  
  2. public object Save_Session(List<Object> aray)  
  3. {  
  4.     string text = "";  
  5.     try  
  6.     {  
  7.         foreach (Dictionary<stringobject> item in aray)  
  8.         {  
  9.             text = new JavaScriptSerializer().Serialize(item);  
  10.         };  
  11.         return text;  
  12.     }  
  13.     catch (Exception ex)  
  14.     {  
  15.         return text;  
  16.     }  

You can see that from here I am also sending the object, which was needed in the success function. You can modify all the codes according to your needs, it's just a simple method.

Now let's run our application and see the output.

Output

On running the application, just open the console and check that controller is hit.


From controller, the factory method is called and from there sample object is send to the WebService:


Now from Web Service again object is send which is retrieved in first function inside "then"

Now this data is returned to controller and there some conditions are checked for this returned data.


According to the conditions fulfilled data is shown on UI.