× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
Alexey Naumov
May 27, 2016
<p>It's really hard to explain promises conception at first. But let's see an example:</p> <pre><code class="language-javascript">function fetchData() { var deferred = $q.defer(); setTimeout(function() { deferred.notify('Send request'); if (true) { deferred.resolve('Success'); } else { deferred.reject('Fail'); } }, 10000); return deferred.promise; } var promise = fetchData(); promise.then( function(value) { $scope.result = value; alert('Success: ' + value); }, function(reason) { alert('Failed: ' + reason); }, function(notification) { alert('Got notification: ' + notification); } );</code></pre> <p>Step by step:<br> <em>var deferred = $q.defer()</em> - it creates deferred object. We can access to promise API through this object.<br> <em>deferred.notify(notification)</em> - it send messages to users. It could be called several times before resolve or reject.<br> <em>deferred.resolve(value)</em> – tell us about success (resolve promise)<br> <em>deferred.reject(reason)</em> – tell us about fail (reject promise)<br> <em>deferred.promise</em> - returns promise object binded to deferred object</p> <p><br> call function:<br> <em>var promise = fetchData();</em> returns promise and save in promise variable<br> <em>promise.then(...)</em> - pass functions for resolve, reject and notify</p> <p>promises states: unresolved, resolved, rejected<br> promises transitions: unresolved -&gt; resolved, unresolved -&gt; rejected</p> <p>resolved and rejected are final states! Promise can't change it's state afterwords!</p> <p>documentation:<br> https://docs.angularjs.org/api/ng/service/$q<br> http://andyshora.com/promises-angularjs-explained-as-cartoon.html</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus