Last active
March 18, 2016 12:32
-
-
Save spbroom/0dac5bca333378b82072 to your computer and use it in GitHub Desktop.
Perpetual Promise Generator for AngularJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
angular | |
.module('app') | |
.factory('getPromiseGenerator', getPromiseGenerator); | |
function getPromiseGenerator($q) { | |
var generator = { | |
whenPromiseResolves: whenPromiseResolves, | |
resolve: resolve | |
}; | |
var deferred = $q.defer(); | |
return function () { | |
return generator; | |
}; | |
function whenPromiseResolves(fn) { | |
(function doThisWhenThePromiseResolves() { | |
deferred.promise.then(function (resolvedWith) { | |
fn(resolvedWith); | |
deferred = $q.defer(); | |
deferred.promise.then(doThisWhenThePromiseResolves); | |
}); | |
})(); | |
} | |
function resolve(resolvedWith) { | |
deferred.resolve(resolvedWith); | |
} | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a perpetual promise generator. Every time the promise is resolved a new one is generated. It could be argued that this is taking liberties with the idea of a promise, but if you think of a promise as asynchronous expectation then this generator simply deals with the situation when one expectation always leads to another and in each case we want to run the same code upon resolving.
so in a controller you might have:
var myPromiseGenerator = getPromiseGenerator();
this.whenSomethingInterstingHappens = myPromiseGenerator.whenPromiseResolves;
this.somethingInterestingHappened = myPromiseGenerator.resolve;
then in the link function of a nested directive (where something interesting might happen):
scope.$watch('somethingOfNote',function(value){
parentCtrl.somethingInterestingHappened(value);
});
and in yet another directive (which is interested in interesting things):
parentCtrl.whenSomethingInterstingHappens(updateThisDirectiveBasedOnAnInterthingEventEveryTIme);