Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is the most basic situation that promises are for. You simply need to make a promise with <code>var deferred = $q.defer()</code> when beginning an async operation, resolve the promise with <code>deferred.resolve(result)</code> when the async operation is complete, and return <code>deferred.promise</code> in your function. Angular's asynchronous methods do this internally and return promises already, so you can just return those same promises rather than creating new promises with <code>$q.defer()</code>. You can attach a <code>.then</code> to anything that returns a promise. Further, if you return a value from a <code>then</code> function, that value will be wrapped in a promise so that the <code>then</code> chain can continue</p> <pre><code>angular.module('myApp', []) .factory('myService', function($q, $timeout, $http) { return { myMethod: function() { // return the same promise that $http.get returns return $http.get('some/url'); } }; }) .controller('myCtrl', function($scope, myService) { myService.myMethod().then(function(resp) { $scope.result = resp.data; }); }) </code></pre> <p>And here is a bit more fun with the chaining:</p> <pre><code>.factory('myService', function($q, $timeout, $http) { return { myMethod: function() { // return the same promise that $http.get returns return $http.get('some/url').then(function() { return 'abc'; }); } }; }) .controller('myCtrl', function($scope, myService) { myService.myMethod().then(function(result) { console.log(result); // 'abc' return someOtherAsyncFunc(); // for example, say this returns '123' }).then(function(result) { console.log(result); // '123' }); }) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload