Categories
Dev JS

Keeping your promises, the AngularJS way

“Always keep your promises” is a common saying which elders suggest would help you in life. But the same could also help keep your AngularJS clean.

Angular JS relies on promises for all of it’s asynchronous operations. Promises are designed to represent the result of an operation which are not yet completed. $http service provides it the promises for HTTP requests.

Most JS applications built will have need for data which are used across the application use time. For e.g. Permissions, Access data, Localization Data and several other settings. Getting the same data for each call from the server can be expensive.

Generally this is handled by fetching the data for the first time and storing it in the memory for Future use. Here is the simple version of it.

The function getData, now when called from any controller will return a promise, which will check data in memory and return it if available, else will make a $http request.

All this looks well, until you have a lot of different services/controllers which need this Data start loading in parallel on application start. As for each of this controller doesn’t find the data in-memory, they make a http call to get the same data. So the seemingly simple fix isn’t so good after all.

Let’s see how we can solve this.

Promises are designed to be containers which get filled by the result of any ongoing async operation. This container can be passed around and data can be read by anyone once the result is obtained into it. This thinking is what makes us move from saving the data obtained to saving the promise generated.

This getData function returns a promise, just like the previous version. But the main difference here is, we are not saving the data returned. We are actually saving the promise and returning it to any service which needs it, which can use the .then on the promise to utilize the data.

This approach makes the method easy to write and also to consume.

To Remember: Be careful to use this approach only when the data returned by the API/ server is expected to remain the same throughout the session / application run time. This is because except for the first call, later calls to the method will not fetch data from server, but just return the data previously fetched.

By Sai Kiran Kothuri

Tech enthusiast. Software Engineer at Microsoft. MS in CS Georgia tech.

Leave a Reply

%d bloggers like this: