Skip to content

Instantly share code, notes, and snippets.

@leon

leon/README.md

Created Feb 4, 2014
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@istarkov 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