【问题标题】:What does it mean to pass 2 functions into '.then()'? (Angular.js)将 2 个函数传递给 '.then()' 是什么意思? (Angular.js)
【发布时间】:2016-04-22 00:12:01
【问题描述】:

我正在阅读一些关于 angular.js 的教程并遇到了这个表达式:

.then(handleRequest, handleRequest)

我想知道将 2 个相同的函数传递给 .then() 是什么意思?

这里有更多上下文:

function MainCtrl(user, auth) {
  var self = this;

  function handleRequest(res) {
    var token = res.data ? res.data.token : null;
    if(token) { console.log('JWT:', token); }
    self.message = res.data.message;
  }

  self.login = function() {
    user.login(self.username, self.password)
      .then(handleRequest, handleRequest)
  }

  ...

}

angular.module('app', [])
.controller('Main', MainCtrl)
....
})();

原始教程可以在这里找到:https://thinkster.io/angularjs-jwt-auth

【问题讨论】:

标签: javascript angularjs angular-promise


【解决方案1】:

then 方法定义为:

promise.then(onFulfilled, onRejected)

第一个参数在 promise 完成时调用。

第二个参数在 promise 被拒绝时调用。

将相同的回调函数作为两个参数传递意味着作者打算使用相同的函数来处理承诺的履行或拒绝。

阅读the complete spec了解更多详情。

【讨论】:

    【解决方案2】:

    第一个用于successCallback,第二个用于errorCallback。所以

    // Simple GET request example:
    $http({
     method: 'GET',
    url: '/someUrl'
    }).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
    }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    });
    

    承诺有点复杂的模式来理解。对我来说最好的资源是

    Promises in AngularJS, Explained as a Cartoon

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多