HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Handling errors of nested promises

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingpromisesnestederrors

Problem

This is in one of my AngularJS controllers:

websiteService.get('websites').then(function(data) {
    $scope.websites = data;
    websiteService.get('groups').then(function(data) {
        $scope.groups = data;
        websiteService.get('websites_groups').then(function(data) {
            $scope.websites_groups = data;
            // If everything goes well, my code will continue here - not really neat
        }, function(error) {
            $scope.errors.push(error);
        });
    }, function(error) {
        $scope.errors.push(error);
    });
}, function(error) {
    $scope.errors.push(error);
});


What would be a better, more elegant way to do this? Is there a best practice?

In my opinion, success functions are nested really nicely, in obvious and chronological and logical order, while error functions make everything messy.

Solution

If I understand correctly, you can unnest your code, and catch any possible error at the end. That's the idea of using promises:

websiteService.get('websites').then(function(data) {
  $scope.websites = data
  return websiteService.get('groups')
}).then(function(data) {
  $scope.groups = data
  return websiteService.get('websites_groups')
}).then(function(data) {
  $scope.websites_groups = data
}).catch(function(error) {
  $scope.errors.push(error)
})

Code Snippets

websiteService.get('websites').then(function(data) {
  $scope.websites = data
  return websiteService.get('groups')
}).then(function(data) {
  $scope.groups = data
  return websiteService.get('websites_groups')
}).then(function(data) {
  $scope.websites_groups = data
}).catch(function(error) {
  $scope.errors.push(error)
})

Context

StackExchange Code Review Q#90559, answer score: 5

Revisions (0)

No revisions yet.