<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="angular-promise-extras.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body data-ng-app="app" data-ng-controller="controller as vm">
<ul>
<li>Successes:{{vm.successes}}</li>
<li>Failures: {{vm.failures}}</li>
<li>allSettled Values: {{vm.values}}</li>
</ul>
</body>
</html>
// Code goes here
(function() {
var _module = angular.module('app', ['ngPromiseExtras']);
function Controller($q) {
var _this = this;
_this.promises = [];
_this.successes = [];
_this.failures = [];
_this.result=null;
for (var i = 0; i < 10; i++) {
var promise = $q.when(i);
if (i === 2 || i == 4) {
promise = $q.reject(i);
}
_this.promises.push(promise);
}
$q.all(_this.promises)
.then(function(done) {
_this.successes.push(done);
console.log("then:", done);
}).catch(function(reject) {
_this.failures.push(reject);
console.log("reject:", reject);
});
_this.values=null;
$q.allSettled(_this.promises).then(function(values){
_this.values=values;
})
}
_module.controller('controller', Controller)
})();
/* Styles go here */
angularjs $q.all reject behavior
(function(angular) {
'use strict';
/**
* Called with an array this acts like map, otherwise it acts like _.mapValues
* in lodash.
* @return {Array|Object} The same type as the input argument.
*/
var mapValues = function(obj, callback) {
if (angular.isArray(obj))
return obj.map(callback)
var ret = {}
Object.keys(obj).forEach(function(key, val) {
ret[key] = callback(obj[key], key)
})
return ret
}
angular.module('ngPromiseExtras', []).config([ '$provide', function($provide) {
$provide.decorator('$q', function($delegate) {
var $q = $delegate
$q.allSettled = function(promises) {
return $q.all(mapValues(promises, function(promiseOrValue) {
if (! promiseOrValue.then)
return { state: 'fulfilled', value: promiseOrValue }
return promiseOrValue.then(function(value) {
return { state: 'fulfilled', value: value }
}, function(reason) {
return { state: 'rejected', reason: reason }
})
}))
}
$q.map = function(values, callback) {
return $q.all(mapValues(values, callback))
}
$q.mapSettled = function(values, callback) {
return $q.allSettled(mapValues(values, callback))
}
/**
* Like Bluebird.resolve.
*/
$q.resolve = function(value) {
if (value && value.then)
return value
else
return $q(function(resolve) { resolve(value) })
}
return $q
})
} ])
})(window.angular)