【问题标题】:Assign value from then function to a variable promise将 then 函数中的值赋给变量 promise
【发布时间】:2015-10-03 15:07:21
【问题描述】:

我正在努力兑现承诺。所以我写了一个如下的示例代码

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

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

【问题讨论】:

  • newdata 是承诺对象,您需要在这些承诺回调之一中分配范围变量。在这种情况下也不需要使用$q,因为$http本身会返回一个promise

标签: angularjs deferred


【解决方案1】:

你的代码有很多问题。首先:你can't return from asynchronous operations,你需要为此使用回调。在您的情况下,由于您使用的是 Promise,因此请使用它的 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
                };
            });
        }
    };
});

【讨论】:

  • 我很困惑何时使用 .then 和 .success。如果可能的话,你能给我介绍一下吗
  • 成功是then(function(response) { return response.data }) 的一种简写形式。我建议始终使用then
  • 什么时候我应该使用 $q.defer ?
  • 当你需要返回一个承诺时,你应该在非承诺函数的情况下使用 defer。 $http、$timeout 之类的东西已经返回了 Promise,所以你不需要多余的 $q.defer。例如,在不返回承诺的自定义函数的情况下,您将使用它。例如jsfiddle.net/97LvLo6e
猜你喜欢
  • 2016-09-15
  • 2018-03-03
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多