如何使用 $q 顺序调用承诺

商品

我想在角度控制器中调用 setup 方法,该方法获取它需要继续的所有相关组件。我确定我应该使用 Promise,但我对正确使用有点困惑。考虑一下:

我有一个 ShellController 需要获取当前登录的用户,然后在屏幕上显示他们的名字,然后获取一些客户详细信息并在屏幕上显示它们。如果这个序列在任何时候失败,那么我需要一个地方让它失败。这是我到目前为止所拥有的(不工作)。

var app = angular.module('app', [])

app.controller('ShellController', function($q, ShellService) {
  var shell = this;
  shell.busy = true;
  shell.error = false;

  activate();

  function activate() {

    var init = $q.when()
      .then(ShellService.getUser())
      .then(setupUser(result)) //result is empty
      .then(ShellService.getCustomer())
      .then(setupCustomer(result)) // result is empty
      .catch(function(error) { // common catch for any errors with the above
        shell.error = true;
        shell.errorMessage = error;
      })
      .finally(function() {
        shell.busy = false;
      });
  }

  function setupUser(user) {
    shell.username = user;
  }

  function setupCustomer(customer) {
    shell.customer = customer;
  }
});

app.service('ShellService', function($q, $timeout) {

  return {
    getUser: function() {
      var deferred = $q.defer();

      $timeout(function() {
        deferred.resolve('User McUserface');
      }, 2000);

      return deferred.promise;
    },
    getCustomer: function() {
      var deferred = $q.defer();

      $timeout(function() {
        deferred.resolve('Mary Smith');
      }, 2000);

      return deferred.promise;
    }
  }

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="ShellController as shell">
    <div class="alert alert-danger" ng-show="shell.error">
      An error occurred! {{ shell.errorMessage }}
    </div>
    <div class="alert alert-info" ng-show="shell.busy">
      Fetching details...
    </div>
    <div>Username: {{ shell.username }}</div>
    <div>Customer: {{ shell.customer }}</div>
  </div>
</body>

我应该在这里做什么?

贡萨洛-

您的代码几乎不需要更改。.then()接收回调引用,而不是另一个承诺。所以在这里

.then(ShellService.getUser())

你传递一个承诺作为参数。您应该传递一个返回解析值或承诺回调作为参数以允许链接

此外,初始$q.when值也不是必需的,因为您的第一个函数已经返回了一个承诺。你应该做这样的事情:

ShellService.getUser()
      .then(setupUser(result)) //result is empty
      .then(ShellService.getCustomer)
      .then(setupCustomer)
      .catch(function(error) { // common catch for any errors with the above
        shell.error = true;
        shell.errorMessage = error;
      })
      .finally(function() {
        shell.busy = false;
      });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章