Tuesday 29 August 2017

$q ,defer and promise example







------------------
var msgDefer = $q.defer();
    msgDefer.promise.then(function (msg) {
        alert("1" + msg);
        return "1";
}
    ).then(function (msg) {
        alert("2" + msg);

    }).catch(function (msg) {
        alert("reject" + msg);
    });




----------


<html>
<head>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/AngularT2.js"></script>
    <script src="~/Scripts/AreaService.js"></script>
</head>
<body ng-app="myapp">
    <div ng-controller="contrlT">
        Result: {{result}}
        Elapsed Time :{{elapsedTime}}
        Failure Reason:{{failure}}
    </div>
    <div ng-controller="cntrl1">
        FirstName:<p>{{firstName}}</p>
        Department:<p>{{department}}</p>
        Area: <b>{{Area}}</b>

    </div>
    <div ng-controller="cnrl2">
     Company: {{company}}
     Department:{{department}}
     Add: {{Add}}
        Divide:{{Divide}}
    </div>

   

</body>
</html>










/// <reference path="angular.min.js" />
var app2 = angular.module("myapp", []);

app2.controller("Parent", function($scope) {
    $scope.$on("myevent", function(event, args) {
        alert("This is parent");
    });

    $scope.SendDownword = function() {
        $scope.$broadcast("myevent", "sent down");
    }

});


app2.controller("contrlT", function($scope, $q) {


    function Add(x, y) {
        var defers = $q.defer();
        var z = x + y;
        if (z >= 0)
            defers.resolve(z);
        else if (z < 0)
            defers.reject("negative values = " + z);
        return defers.promise;
    }
    var starttime = Date.now();
    Add(4, 5).then(function(result) {
            $scope.result = result;
            $scope.elapsedTime = Date.now() - starttime;
        })
        .catch(function(failure) {
            $scope.failure = failure;
        })
        .finally(function() {
            $scope.elapsedTime = "changed time";
        })

    //function Add(x, y,callback1)
    //{
    //    $timeout(function () { callback1(x + y); }, 100)

    //}

    //var starttime = Date.now();
    //Add(5, 6, function (result) {
    //    Add(result, 66, function (result) { 
    //    $scope.result = result;
    //    $scope.elapsedTime = Date.now() - starttime;
    //    });
    //});



    //var deferT = $q.defer();
    //deferT.promise
    //.then(function (msg) {
    //    alert("promise  alert" + msg);
    //    return "2";
    //}).then(function (msg) {

    //    alert("promise alert" + msg);
    //    throw Ex;
    //}, function (msg1) {
    //    alert(msg);
    //})



    //deferT.resolve("1");
    //deferT.reject("exeception occured");
});

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0