Understanding Angular JS promises

Promises are one of the most powerful concepts for Angular and JavaScript. They enable your application to perform other tasks while waiting for the result of another operation. According to the official documentation, A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

When do we use promises?

When we need to make a request, load some data or perform some other sort of operation, but we don’t know when / if we get the result.

There are three possible outcomes to making a promise request. First two are a promise that was fulfilled : Success, we get the expected result OR Error, we get a false of some sort.

The final option is the promise was rejected, an error was thrown.

This is all fine, but personally I’ve had a few issues first understanding promises, so let’s try to explain these in a simple way:

Promises and your tax return

Since the new fiscal year started, let’s do a tax return story.

We need to submit our tax returns, so we do this by using an accountant.

We get all our documents and then we give them to our accountant. She promises she will get the outcome in 3 working days.

That’s our request done and since we don’t just hang around the accountant’s office, we can do all sorts of other things, since the request is asynchronous.

So a few days later we get one of the possible outcomes from the accountant:

  1. The accountant says all documents are there, your tax return has been submitted, so we have a success.
  2. He tells us not all documents are here, some are missing and we need to fix it first, so we have an error, but a proper response from our request.
  3. The accountant has taken all our documents and those of other clients, emptied their bank accounts (not ours, phew…) and left to a third party unnamed tropical country without an extradition treaty to enjoy the illegal proceeds and have a relaxing life ūüôĀ ohhh…. So we don’t even get a reply to our request… plus… we don’t have copies of our receipts! Ouch…

Hopefully that clears it up a bit. But let’s look at some actual code.

Here are the controller and the service:

Controller:

//function in accountantController.js
var startAccountantPromise = function() {
    //Imagine we have an accountantService somewhere that handles the requests and other operations.
    //This function returns a promise which we will deal with here    
    accountantService.submitTaxReturn()
        // then() - this function is always called when we get a response
        .then(function(data) {
            // our promise was fulfilled. We don't know which of the possible outcomes though, so we need to check
            if (data.taxReturn === 'accepted') {
                //weeeee, all good, so we... get on with our lives
                enjoyLifeAndRelax();
            } else {
                // since the status is not 'accepted' it can be other stuff so... we need to check for missing documents
                checkMissingTaxReturnDocuments();
            }
        }, function(error) {
            //the final option is the promise was rejected, caused by some sort of error
            //we can log to the console like this : console.log('error', error);
            startPanicking();
        });
};

So that’s the controller, but that uses some functions that we need to see.

Service

app.factory('accountantService', function ($http, $q) {
    return {
        submitTaxReturn: function() {            
            //the $http API is based on the deferred/promise APIs exposed by the $q service and it returns a promise by default
            //documentation here : https://docs.angularjs.org/api/ng/service/$http
            return $http.get('http://honest-accountant-api-service.com/submit-your-tax-return')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        //oops, invalid response...
                        return $q.reject(response.data);
                    }
                }, function(response) {
                    //something went wrong, where is our accountant?!?!?
                    return $q.reject(response.data);
                });
        }
    };
});

Summary

Hopefully this little story demonstrated the asynchronous nature of the request we make. We don’t need to wait at the accountant’s office, we can perform other operations in the meantime.

When we give our documents we immediately get a promise, so we expect to hear back at some point.

The accountant is dealing with our request and all the operations on that end are abstracted from us as financial stuff is wizardry. We don’t need to know how the stuff is resolved, we only need to hear back the result.

ūüôā


Angular JS, Understanding $emit, $broadcast and $on

In late 2015 I started working with Angular JS as part of a project at work (Hybrid mobile app).

Understanding the concepts is quite important to make use of it in an efficient and extendable way.

Angular JS provides us with some events that we can use to communicate between controllers.

They are $on, $emit and $broadcast.

Here is a quick schematic on the direction of the events.

$on

When using $on, Angular listens to an event of a given type. We can call it anyway we want. $on will catch any event dispatched by $emit or $broadcast.

Real life example from a hybrid app:

$scope.$on(AUTH_EVENTS.notAuthorized, function(event) {
 //do something to block the unauthorized page view attempt
 });
});

(AUTH_EVENTS is a constant we are using in our app)

So what happens and how / where does this happen?

In an authentication service, the user is checked if logged in. If he / she is not, we will emit an event which will block the unauthorized page view.

So we need to broadcast this event:

$scope.$broadcast('AUTH_EVENTS.notAuthorized', { ... });

Since we mentioned broadcast, let’s quickly go through that.

$broadcast

Broadcast dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

$broadcast(name, args);

The event cannot be cancelled. The event starts at the scope on which $broadcast was called. All listeners for the event get notified, all events under the scope.

$emit

 is pretty much the same thing, just in reverse (going upwards into the $scope).

It will traverse all the $scopes until the $rootScope.

Unlike the $broadcast event, this one can be cancelled by any of the listeners.

Do try to keep the $rootScope clean ūüôā