Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS : Where to use promises?
    text
    copied!<p>I saw some examples of Facebook Login services that were using <strong>promises</strong> to access FB Graph API. </p> <p><strong>Example #1</strong>:</p> <pre><code>this.api = function(item) { var deferred = $q.defer(); if (item) { facebook.FB.api('/' + item, function (result) { $rootScope.$apply(function () { if (angular.isUndefined(result.error)) { deferred.resolve(result); } else { deferred.reject(result.error); } }); }); } return deferred.promise; } </code></pre> <p>And services that used <code>"$scope.$digest() // Manual scope evaluation"</code> when got the response </p> <p><strong>Example #2</strong>:</p> <pre><code>angular.module('HomePageModule', []).factory('facebookConnect', function() { return new function() { this.askFacebookForAuthentication = function(fail, success) { FB.login(function(response) { if (response.authResponse) { FB.api('/me', success); } else { fail('User cancelled login or did not fully authorize.'); } }); } } }); function ConnectCtrl(facebookConnect, $scope, $resource) { $scope.user = {} $scope.error = null; $scope.registerWithFacebook = function() { facebookConnect.askFacebookForAuthentication( function(reason) { // fail $scope.error = reason; }, function(user) { // success $scope.user = user $scope.$digest() // Manual scope evaluation }); } } </code></pre> <p><a href="http://jsfiddle.net/mkotsur/Hxbqd/" rel="noreferrer">JSFiddle</a> </p> <p>The questions are: </p> <ul> <li>What is the <strong>difference</strong> in the examples above? </li> <li>What are the <strong>reasons</strong> and <strong>cases</strong> to use <em>$q</em> service?</li> <li>And how does it <strong>work</strong>?</li> </ul>
 

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