Skip to content

Instantly share code, notes, and snippets.

@spbroom
Last active March 18, 2016 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spbroom/0dac5bca333378b82072 to your computer and use it in GitHub Desktop.
Save spbroom/0dac5bca333378b82072 to your computer and use it in GitHub Desktop.
Perpetual Promise Generator for AngularJs
(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);
}
}
})();
@spbroom
Copy link
Author

spbroom commented Mar 18, 2016

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment