Server Grab Pattern

Terrible name, I know. But I've been digging this pattern for succinctly and simultaneously getting data from the server and putting it on the $scope.

I present the Server Grab Pattern:

// inside a controller (or whatever. you get the idea):
$q.all({
    users:   api.get('users'),
    books:   api.get('books'),
    bananas: api.get('fruit').then(function (fruit) {
        return _.pluck(fruit, 'banana');
    }
}).then(function (responses) {
    angular.extend($scope, responses);
}).catch(errorHandler);

The idea here is that it's a very clear way to simultaneously grab a bunch of stuff from the server, maybe do individual manipulations before attaching to the $scope where it's clear where each piece goes, etc, etc.

And then in one line in the response, you put everything on the $scope and you can handle all the errors at once. Once I started using this, I cut down on a lot of lines of code and I personally find it easier to read than what I was using before, too.

What's Happening

$q.all can take an array or map of promises (they don't even actually have to be promises!) and runs them all asyncronously and once all of those promises are returned, then it passes the array/map with the resolved values to the then handler. Since you can chain promises, you can arbitrarily do something with just certain responses and they could even return promises (or not, like in this example, as this example makes it clearer that we're manipulating that data straight from the server).

Yeah, I think promises are pretty dang awesome, too.

It's just a cool little pattern I've been using and wanted to share. Ya know. Since it's 11:37pm on June 30th and my goal was to write 2 posts every month this year...