What are AngularJS Promises
AngularJS Promises are a fascinating and integral component of the Angular framework. They offer an extremely robust and advanced mechanism of application control, and as complexity begins to scale up, you as an AngularJS Developer will find that promises are nearly impossible to ignore.This, however, is a good thing; promises are extraordinarily powerful, and they will make your life much simpler once they’re fully understood.
AngularJS Promises ecosystem can be more readily decoded by gaining a better understanding of the nomenclature behind it, and what problems it intends to solve.
nested callbacks, colloquially referred to as callback hell.
In this article I’ll make an Angular Controller and a factory. The factory will call the Github API to fetch single user details. Instead of executing a callback, the factory will return a promise, which can be utilised in the Controller.
In the above snippet, the factory is making an Asynchronous call to the Github API , but it doesn’t returns the data directly. Here comes AngularJS Promises in the picture. The fetchUser function returns the promise, and when the Asynchronous call is done, it resolve or rejects the promise accordingly.
Key points from the Snippet
A deferred is the interface through which the application will set and alter the state of the promise. An AngularJS deferred object has exactly one promise attached to it by default, which is accessible through the promise property.
A promise represents an unknown state that could transition into a known state at some point in the future. A promise represents an unknown state that could transition into a known state at some point in the future.
- 0 : This is the pending state that represents an unfulfilled promise waiting for evaluation. This is the initial state.
- 1 : This is the resolved state that represents a successful and fulfilled promise. A transition to this state cannot be altered or reversed.
- 2 : This is the rejected state that represents an unsuccessful and rejected promise caused by an error. A transition to this state cannot be altered or reversed.
I hope this article will help you to understand and implement AngularJS Promises. Please leave your query in the comment section below.