Skip to content

Instantly share code, notes, and snippets.

@Aaronius
Last active March 29, 2021 09:12
Show Gist options
  • Save Aaronius/46ae4a0f8ff052cd24f0 to your computer and use it in GitHub Desktop.
Save Aaronius/46ae4a0f8ff052cd24f0 to your computer and use it in GitHub Desktop.
Angular $q allSettled() implementation similar to https://github.com/kriskowal/q/wiki/API-Reference#promiseallsettled
angular.module('qAllSettled', []).config(function($provide) {
$provide.decorator('$q', function($delegate) {
var $q = $delegate;
$q.allSettled = function(promises) {
return $q.all(promises.map(function(promise) {
return promise.then(function(value) {
return { state: 'fulfilled', value: value };
}, function(reason) {
return { state: 'rejected', reason: reason };
});
}));
};
return $q;
});
});
@ryanhart2
Copy link

$q.all accepts an array or hash of promises, whereas this implementation of allSettled will only work when promises is an array of promises. An alternative could be as follows:

      $q.allSettled = function(promises) {
        var wrappedPromises = angular.isArray(promises) ? promises.slice(0) : {};
        angular.forEach(promises, function(promise, index){
          wrappedPromises[index] = promise.then(function(value){
            return { state: 'fulfilled', value: value };
          }, function(reason){
            return { state: 'rejected', reason: reason };
          })
        });
        return $q.all(wrappedPromises);
      };

@insidewhy
Copy link

@ryanhart2 Your version is better but it should also consider "non-thenables" as successfully resolved values.

Implemented this and added it to the bower registry:

https://github.com/ohjames/angular-promise-extras

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