Tuesday, September 29, 2015

Resolve Angular promises multiple times

As you know that a promise can only be resolved once. While building a framework for my application, I came into a requirement that I need to resolve the same promise multiple times. In order to resolve the same promise multiple times, I found a hack solution that works.

First I clone the original promise object (actually the promise state). I will then clone this promise and then keep resolving this when needed. Here is the code that does this:

    if (promiseState === undefined)
        promiseState = angular.copy(deferred.promise.$$state);
    angular.extend(deferred.promise.$$state, promiseState)
    deferred.resolve();

In the above code, I am using promiseState to keep a copy of the original promise state. I am using kind of singleton pattern to store the promise state. Before resolving the promise, I clone the original promise state and override the current promise state. With this trick I was able to resolve the same promise multiple times.

Here is the complete code. You can also get this code at this Plunker (http://plnkr.co/edit/HsTpGIcxAHwvYAH3UGbQ?p=preview)

<html>
<head>
    <title>Resolve Angular promises multiple times</title>
</head>
<body ng-app="multipleResolves">
    <div ng-controller="index as vm">
        Click the button below to resolve a promise. Every click will resove the same promise again, thereby resolving a promise multiple times
        <br /><br />
        <button ng-click="vm.resolve()">Resolve</button>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script>
        angular.module('multipleResolves', [])
        .controller("index", index);
        function index($scope, $q) {
          var deferred, promiseState

            var vm = {
              resolve: resolve
            }

            init();
            return vm;

            function init() {
                angular.extend($scope, vm);

                //creating the $q
                deferred = $q.defer();

                deferred.promise.then(function(){
                  alert('resolved');
                })
            }

            function resolve() {
                // below three lines are the key for resolving a promise multiple times
                 if (promiseState === undefined)
                     promiseState = angular.copy(deferred.promise.$$state);
                 angular.extend(deferred.promise.$$state, promiseState)
              deferred.resolve();
            }

        }
    </script>
</body>
</html>

No comments:

Post a Comment