Skip to content

Instantly share code, notes, and snippets.

@leon
Created February 4, 2014 09:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leon/8800809 to your computer and use it in GitHub Desktop.
Save leon/8800809 to your computer and use it in GitHub Desktop.
angularjs $q decorator for spread

Use it like this

$q.all([ promise1, promise2 ]).then($q.spread(function (promise1Result, promise2Result) {

});

'use strict';
angular.module('common.decorators').config(function ($provide) {
var resolveWith = function($q) {
return function resolved(val) {
var dfd = $q.defer();
dfd.resolve(val);
return dfd.promise;
};
};
$provide.decorator('$q', 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;
});
});
@istarkov
Copy link

istarkov commented Jul 5, 2014

Thank you for your code,
Please add return statement before targetFn.apply(scope, params);
elsewhere next ".then" after .spread is not working

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