| Start |
|---|
| Wrap simple value into a promise using $q.when() If all you need is to wrap the value into a promise, you don't need to use the long syntax like here: In this case you can just write: $q.when and its alias $q.resolveWraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. [— AngularJS $q Service API Reference - $q.when](https://docs.angularjs.org/api/ng/service/$q#when)With the release of AngularJS v1.4.1 You can also use an ES6-consistent alias |
| Using angular promises with $q service
In our example, we call our factory In Angular factory Using Promises on callTo use promises, inject A new instance of deferred is constructed by calling A deferred object is simply an object that exposes a promise as well as the associated methods for resolving that promise. It is constructed using the
PropertiesThe associated promise object is accessed via the promise property.
A new promise instance is created when a deferred instance is created and can be retrieved by calling The purpose of the Promise Methods - One of the most powerful features of promises is the ability to chain them together. This allows the data to flow through the chain and be manipulated and mutated at each step. This is demonstrated with the following example: Example 1: |
| Using the $q constructor to create promises The $q(function(resolve, reject) {...}) The constructor function receives a function that is invoked with two arguments, Example 1: The above example creates a promise from the WindowTimers.setTimeout API (opens new window). The AngularJS framework provides a more elaborate version of this function. For usage, see the AngularJS $timeout Service API Reference (opens new window). Example 2: The above code showing a promisified division function, it will return a promise with the result or reject with a reason if the calculation is impossible. You can then call and use |
| Using $q.all to handle multiple promises You can use the Example: JS: The above code runs The data is then mapped so it could be shown on the template, we can then show HTML: JSON: |
Avoid the $q Deferred Anti-Pattern Avoid this Anti-PatternThere is no need to manufacture a promise with Simply return the promise created by the $http service. |
| Deferring operations using $q.defer We can use This method is not equivalent of using the Example: |
Read Article
https://develop.horje.com/learn/1434/reference