Assign value from then function to a variable promise

你离开我真会死。 提交于 2020-01-23 11:53:13

问题


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??


回答1:


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
                };
            });
        }
    };
});


来源:https://stackoverflow.com/questions/32924048/assign-value-from-then-function-to-a-variable-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!