Angular’s $q.defer() Example

If you are familiarized with promises this will be a piece of cake. If not, it will be a piece of muffin :)

Let’s gif this thing up

Ok, let’s be honest, tutorials and examples are typically pretty boring. So let’s do the following: let’s build a chat room where every time you write something, it replaces that text with a gif! To do that, we will be communicating with Giphy’s API.

My code structure

Index.html → my view.

MainController.js → define Angular app and code for my (only) controller.

getDataService.js → a service I will use to get my data from Giphy!

Let’s get some gifs!

First, let’s make sure we can get some gifs. Since the getDataService will be the file handling all interactions with Giphy’s API, let’s start there:

There you have it! Console-logging the results will give you a nice object containing an array of ~25 (max) GIFs.

Ok cool, but I don’t want to have the searchQuery hardcoded on my service, I want the user to type the query and pass that to my service through my controller. Let’s do that.

My index.html:

My MainController:

My getDataService:

This works and stuff, but… how do I pass the data back to the controller? You can pass a callback to the service or you can use promises!

Angular’s $q.defer() promises

A promise object is used for deferred and asynchronous computations. The key here is the word asynchronous. The simplified version is that putting an API request takes time to get back to you. Javascript has no idea when that time will be, and does not want to sit around on that line of code until data comes back.

Promises allows Javascript to move forward reading the code, and whenever data comes back, execute Javascript code (and reflect the changes on the front end — which is what we want).

For this, we’ll have to make a couple of modifications to our service and to our controller.

The service will return a promise to the controller, and once the service gets the data, the controller will do something with that data (on our case, we want it to make a change on our view).

All together now: My service (remember to inject $q):

My controller:

My index.html:

The end result :)

--

--