将 then 函数的值赋给变量 promise

Assign value from then function to a variable promise

我正在努力争取承诺。所以我写了如下示例代码

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

我在这里尝试 return 从 then 函数获取的数据并将其分配给一个变量。但是我得到一个 $$ 状态对象,它有一个保存数据的值键。是可以直接赋值还是在 then 函数中我需要使用作用域对象然后访问数据??

你的代码有很多问题..首先:你can't return from asynchronous operations,你需要为此使用回调。在你的情况下,因为你使用的是承诺,所以使用它的 then API 。在其回调中,您可以将数据分配给变量。 Angular 将完成其余的同步范围绑定(通过 运行 新摘要)。

下一个问题:不要使用$q.defer(),你根本不需要它。这是最流行的anti-pattern.

还有一件事:不要在控制器中发出任何 http 请求,这不是它的正确位置。而是将此逻辑移至可重用服务。

整体看起来像这样:

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