我是不是正确返回这个诺言? [英] Am I returning this promise correctly?

查看:118
本文介绍了我是不是正确返回这个诺言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,getMonitors一个服务里面。 getMonitors返回监控对象的列表。如果显示器的对象是空的,它通过http抓住显示器和存储监控对象数组中的对象,然后返回。该功能为codeD当成了承诺。我知道HTTP返回一个承诺,但我的功能可能会或可能不会使用http - 所以我用我自己的诺言覆盖(请参阅下面的code)

I have a function, getMonitors inside a service. getMonitors returns a list of monitor objects. If the monitor object is empty, it grabs the monitors via http and stores the objects in a monitor object array and then returns it. The function is coded as a promise. I know http returns a promise, but my function may or may not use http - so I've overlaid it with my own promise (see below for code)

控制器可以调用getMonitors(0)或getMonitors(1)。 0意味着,如果其已加载的显示器阵列由于previous电话,不要再加载它。 (1)指力重新从HTTP

Controllers can call getMonitors(0) or getMonitors(1). 0 means if its already loaded in the monitors array due to a previous call, don't load it again. (1) means force reload the array from HTTP

服务和相关getMonitors为codeD方式如下:

The service and associated getMonitors is coded the following way:

angular.module('zmApp.controllers').service('ZMDataModel', ['$http', '$q',
      function($http, $q) {
        // var deferred='';
        var monitorsLoaded = 0;
        var monitors = [];

        getMonitors: function(forceReload) {
          console.log("** Inside ZMData getMonitors with forceReload=" + forceReload);
          var d = $q.defer();
          if ((monitorsLoaded == 0) || (forceReload == 1)) // monitors are empty or force reload
          {
            console.log("ZMDataModel: Invoking HTTP Factory to load monitors");
            var apiurl = loginData.apiurl;
            var myurl = apiurl + "/monitors.json";
            $http.get(myurl)
              .success(function(data) {
                // console.log ("HTTP success got " + JSON.stringify(data));
                monitors = data.monitors;
                console.log("promise resolved inside HTTP success");
                monitorsLoaded = 1;
                return d.resolve(monitors);
              })
              .error(function(err) {
                console.log("HTTP Error " + err);
                monitors = [];
                console.log("promise resolved inside HTTP fail");
                // I know I need to reject here, not resolve. I'll get to it. For now lets assume I need an empty monitors list if there was an error
                return d.resolve(monitors);
              });
            console.log("promise deferred inside HTTP inside getMonitors");
            return d.promise;

          } else // monitors are loaded
          {
            console.log("Returning pre-loaded list of " + monitors.length + " monitors");
            return d.resolve(monitors);
          }

        },

我已经设置了getMonitors像这样的依赖路线:

I have a route set up with getMonitors as a dependency like so:

.state('app.montage', {
  data: {
    requireLogin: false
  },
  resolve: {
    message: function(ZMDataModel) {
      console.log("Inside app.montage resolve");
      return ZMDataModel.getMonitors(0);
    }
  },
  url: "/montage",
  views: {
    'menuContent': {
      templateUrl: "templates/montage.html",
      controller: 'zmApp.MontageCtrl',

    }
  }
})

使用这个样本控制器是codeD,像这样:

A sample controller that uses this is coded like so:

angular.module('zmApp.controllers').controller('zmApp.MontageCtrl', function($scope, $rootScope, ZMDataModel, message) {

  $scope.monitors = [];
  console.log("Inside MontageCtrl waiting for monitors to load...");

  $scope.monitors = message;
  // this line returns undefined when getMonitors tries to return a preloaded monitor list
  console.log("I have received the monitors inside Montage and there are " + $scope.monitors.length);
  // console.log("***CALLING FACTORY");
  //ZMHttpFactory.getMonitors().then(function(data) //{
  //                                  $scope.monitors = data;
  // console.log("I GOT " + $scope.monitors);
  //    });

  $scope.doRefresh = function() {
    console.log("***Pull to Refresh");
    $scope.monitors = [];

    var refresh = ZMDataModel.getMonitors(1);
    refresh.then(function(data) {
      $scope.monitors = data;
      $scope.$broadcast('scroll.refreshComplete');
    });

  };
});

我面临的问题是,这是第一次运行时,显示器列表是空的,所以ZMData从HTTP URL加载监视器和视图完美展现。当我切换到另外的看法,回到这个观点,我把它记录了ZMData正在恢复显示器的preloaded列表(我知道他们正在填充,因为我打印出在ZMData getMonitor其他部分的计数)。然而,被返回到控制器是不确定的,当getMonitors的else部分的打击。

The problem I am facing is that the first time this is run, the monitors list is empty so ZMData loads the monitors from the HTTP url and the view shows perfectly. When I switch to another view and back to this view, I see it logs that ZMData is returning the preloaded list of monitors (I know they are populated because I am printing out the count in ZMData getMonitor else section). However, what is being returned to the controller is undefined when the "else" part of getMonitors hit.

这可能意味着我不是getMonitors正确返回的承诺别人的一部分。

This likely means I am not returning the promise correctly in getMonitors "else" part.

任何帮助将AP preciated

Any help would be appreciated

推荐答案

嗯,我终于包裹着我身边的诺言的头。
我们不能回到d.resolve()。这只是设置的状态。你总是需要返回d.promise,它如果得到解决,它将返回的决心。人。这驱使我mad.I想,我终于得到了承诺的基本窍门后3个不同的做题。我希望做更清楚的教程。每个人都只能回到d.promise,没有人真正解释清楚,d.promise返回承诺的状态 - 这是由决心改变或拒绝

Ah, I finally wrapped my head around promises. We can't return d.resolve(). That just sets a state. You always need to return d.promise and it if was resolved, it will return the resolve. Man. This drove me mad.I think I finally got the basic hang of promises after 3 different SO questions. I wish tutorials made this clearer. Everyone was only returning d.promise and no one really explained clearly that d.promise returns the state of the promise - which is changed by resolve or reject.

正确的code是:

getMonitors: function (forceReload) {
            console.log ("** Inside ZMData getMonitors with forceReload="+forceReload);
            var d = $q.defer();
           if ((monitorsLoaded == 0) || (forceReload == 1)) // monitors are empty or force reload
           {
               console.log ("ZMDataModel: Invoking HTTP Factory to load monitors");
                var apiurl = loginData.apiurl;
                var myurl = apiurl+"/monitors.json";
                $http.get(myurl)
                    .success(function(data)
                    {
                       // console.log ("HTTP success got " + JSON.stringify(data));
                        monitors = data.monitors;
                        console.log ("promise resolved inside HTTP success");
                        monitorsLoaded = 1;
                        d.resolve(monitors);
                    })
                    .error (function (err)
                    {
                        console.log ("HTTP Error " + err);
                        monitors = [];
                        console.log ("promise resolved inside HTTP fail");
                        d.resolve (monitors);
                });
                return d.promise;

           }
            else // monitors are loaded
            {
                console.log ("Returning pre-loaded list of "+monitors.length+" monitors");
                 d.resolve(monitors);
                return d.promise;
            }

        }

这篇关于我是不是正确返回这个诺言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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