Created
March 23, 2014 15:51
-
-
Save ThomasBurleson/9724999 to your computer and use it in GitHub Desktop.
Decorate the AngularJS $q instance to inject spread() and resolve() functionality.
This file contains hidden or 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
/** | |
* @author Thomas Burleson | |
* @date November, 2013 | |
* @copyright 2013 Mindspace LLC. | |
* @web http://solutionOptimist.com | |
* | |
* @description | |
* | |
* Used within AngularJS to decorate/enhance the AngularJS `$q` service. | |
* | |
* | |
*/ | |
(function ( window ){ | |
"use strict"; | |
/** | |
* Decorate the $q service instance to add extra | |
* `spread()` and `resolve()` features | |
*/ | |
var $QDecorator = function ($provide) | |
{ | |
// Partial application to build a resolve() function | |
var resolveWith = function( $q) | |
{ | |
return function resolved( val ) | |
{ | |
var dfd = $q.defer(); | |
dfd.resolve( val ); | |
return dfd.promise; | |
}; | |
}; | |
// Register our $log decorator with AngularJS $provider | |
$provide.decorator('$q', ["$delegate", | |
function ($delegate) | |
{ | |
if ( angular.isUndefined( $delegate.spread )) | |
{ | |
// Let's add a `spread()` that is very useful | |
// when using $q.all() | |
$delegate.spread = function( targetFn,scope ) | |
{ | |
return function() | |
{ | |
var params = [].concat(arguments[0]); | |
targetFn.apply(scope, params); | |
}; | |
}; | |
} | |
if ( angular.isUndefined( $delegate.resolve )) | |
{ | |
// Similar to $q.reject(), let's add $q.resolve() | |
// to easily make an immediately-resolved promise | |
// ... this is useful for mock promise-returning APIs. | |
$delegate.resolve = resolveWith($delegate); | |
} | |
return $delegate; | |
} | |
]); | |
}; | |
if ( window.define != null ) | |
{ | |
window.define([ ], function ( ) | |
{ | |
return [ "$provide", $QDecorator ]; | |
}); | |
} else { | |
window.$QDecorator = [ "$provide", $QDecorator ]; | |
} | |
})( window ); |
Thank's for that must-have helpers!
Thanks for the simple decorator! I forked it and made one minor change, to return the result from the applied function (line 51). I was running this and wondered why my promise chain was breaking after $q.spread. 😄
Found this via an egghead.io video and the associated github repo.
I've tried to use this as you've suggested above, including agates' tweak, and it doesn't want to work with Angular 1.4. The error I'm getting amounts to "argument is not a function" when I try to configure it as you suggest. I'm still an Angular newbie, any suggestions you can give in terms of making this go because it's exactly what I seem to need. Thanks!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then it is super easy to configure this decorator within AngularJS: