将值从函数赋值给变量promise [英] Assign value from then function to a variable promise

查看:94
本文介绍了将值从函数赋值给变量promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力兑现诺言.所以我写了下面的示例代码

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>

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

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

推荐答案

您的代码有很多问题..开始于:您

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).

下一个问题:不要使用$q.defer(),您根本不需要它.这是最受欢迎的反模式.

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

另一件事:不要在控制器中发出任何http请求,这不是正确的选择.而是将此逻辑移至可重用服务.

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

这篇关于将值从函数赋值给变量promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆