2

I am trying to get hands in promises. SO i wrote a sample code like below

<!doctype html>
<html  ng-app="myApp">
  <head>
    <meta charset="UTF-8"> 
    <script src="../angularjs.js"></script>
  </head>
  <body>
    <div ng-controller="CartController">
    </div>

  <script>
    var app = angular.module('myApp', []);

    app.controller('CartController',  function($scope, $q,$http){   

    $scope.newFun = function()
    {
      var defered = $q.defer();
      $http.get('data.json').success(function(data) {
        console.log(data);
        defered.resolve(data);
      })
      .error(function(data, status) {
        console.error('Repos error', status, data);
      });
      return defered.promise;
     }

     var newdata = $scope.newFun().then(
      function(data1) 
      {
        //console.log(data1);
        return data1;
      });

      console.log(newdata);
    });
  </script>
  </body>
</html>

Here i am trying to return the data got from the then function and assign it to a variable. But i am getting a $$ state object, which has a value key which holds the data. Is directly assigning the value is possible or inside the then function i need to use scope object and then access the data??

Hacker
  • 7,798
  • 19
  • 84
  • 154
  • `newdata` is promise object, you need to assign scope variables within one of those promise callbacks. Also no need to use `$q` in this instance since `$http` returns a promise itself – charlietfl Oct 03 '15 at 15:15

1 Answers1

4

Many problems with your code.. To start with: you can't return from asynchronous operations, you need to use callbacks for this. In your case since you are using promises use then API of it. Inside of its callback you would assign your data to variable. Angular will do the rest synchronizing scope bindings (by running new digest).

Next problem: don't use $q.defer(), you simply don't need it. This is the most popular anti-pattern.

One more thing: don't make any http requests in controller, this is not the right place for it. Instead move this logic to reusable service.

All together it will look something like this:

var app = angular.module('myApp', []);

app.controller('CartController', function ($scope, data) {
    data.get().then(function (data) {
        var newdata = data;
    });
});

app.factory('data', function($http) {
    return {
        get: function() {
            return $http.get('data.json').then(function (response) {
                return response.data;
            }, function (err) {
                throw {
                    message: 'Repos error',
                    status: err.status, 
                    data: err.data
                };
            });
        }
    };
});
Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I am very much confused when to use .then and .success. If possible can you brief me – Hacker Oct 03 '15 at 16:33
  • Success is sort of shorthand for `then(function(response) { return response.data })`. I would recommend always use `then`. – dfsq Oct 03 '15 at 16:45
  • When is the ideal situation when i should use $q.defer ? – Hacker Oct 03 '15 at 16:51
  • You should use defer in case of non-promise functions when you need to return a promise. Things like $http, $timeout already return promises, so you don't need redundant $q.defer. You would use it for example in case of custom function that doesn't return promise. For example http://jsfiddle.net/97LvLo6e/ – dfsq Oct 03 '15 at 17:14