Book Image

AngularJS Web Application Development Blueprints

By : Vinci J Rufus
Book Image

AngularJS Web Application Development Blueprints

By: Vinci J Rufus

Overview of this book

Table of Contents (17 chapters)
AngularJS Web Application Development Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using promise for asynchronous calls


We know that services are always lazily loaded and are executed asynchronously. Two ways to deal with such asynchronous calls are using callbacks and promises.

While callbacks are OK when making individual requests, they tend to get messy when you need to do nested callbacks. This is where promises come in handy, as they can be easily chained.

As per the proposal at CommonJS, "Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time."

Promises in AngularJS are implemented via the $q service, which is based on the Q Library by Kris Kowal. It is available at https://github.com/kriskowal/q.

There are two components to this: Deferred and Promise. The Deferred object is used to notify the status of the task. The Promise object provides the result of the deferred task.

The Deferred object has three methods: resolve(...