不清楚参数传递的承诺模型

时间:2016-09-10 08:53:49

标签: angularjs

我是angularjs的新手。我对AngularJS中的承诺模型如何工作感到困惑。下面的示例是我从github找到的教程代码。我可以混淆then()中的参数“response”来自何处以及它是如何工作的?请有人向我解释一下!

(function () {
    'use strict';

    angular
        .module('app')
        .controller('RegisterController', RegisterController);

    RegisterController.$inject = ['UserService', '$location', '$rootScope'];
    function RegisterController(UserService, $location, $rootScope) {
        var vm = this;

        vm.register = register;

        function register() {
            vm.dataLoading = true;
            UserService.Create(vm.user)
                .then(function (response) { // where response comes from?
                    if (response.success) {
                        // FlashService.Success('Registration successful', true);
                        console.log('Registration successful')
                        $location.path('/login');
                    } else {
                        // FlashService.Error(response.message);
                        console.log(response.message);
                        console.log('get error when register users')
                        vm.dataLoading = false;
                    }
                });
        }
    }

})();

1 个答案:

答案 0 :(得分:1)

它称为Promise - 它取代了异步方法的良好旧回调样式。 UserService.Create不是将回调传递给UserService.Create,而是返回一个承诺,您可以决定它后面的内容(一旦解决或拒绝)。 promise有方法then()接受2个参数:

  1. 处理已解决的承诺的功能
  2. 处理被拒绝承诺的功能
  3. 在多个回调的情况下,它简化了您的流程+打破回调金字塔。

    Angular使用名为q的库: https://github.com/kriskowal/q