如何在AngularJs中使用相互依赖的并行和顺序函数调用?

时间:2017-06-11 08:45:05

标签: javascript angularjs asynchronous promise

服务

(function () {
    'use strict';

    angular
        .module('app.user')
        .factory('myService', Service);

    Service.$inject = ['$http', 'API_ENDPOINT', '$q'];

    /* @ngInject */
    function Service($http, API_ENDPOINT, $q) {


        var getUserDetails = function (paramData) {
            return $q(function (resolve, reject) {
                $http.get(API_ENDPOINT.url + '/user/details', paramData).then(function (result) {
                    if (result.data.success) {
                        resolve(result.data);
                    } else {
                        reject(result.data.msg);
                    }
                });
            });
        };

        var getCountryDetails = function (paramData) {
            return $q(function (resolve, reject) {
                $http.get(API_ENDPOINT.url + '/country/details', paramData).then(function (result) {
                    if (result.data.success) {
                        resolve(result.data);
                    } else {
                        reject(result.data.msg);
                    }
                });
            });
        };


        return {
            getUserDetails: getUserDetails,
            getCountryDetails: getCountryDetails
        };
    }
})();

控制器

(function () {
    'use strict';

angular
    .module('app.user')
    .controller('myService');

/* @ngInject */
function UserCtrl(userService,countryService) {
    var vm = this;

    vm.onCountryChange = function (id) {
        vm.states = vm.countries.filter(function (item) {
            return item.id === id;
        })[0].states;
    };

    function init() {

        var token = window.localStorage.getItem('TOKEN');
        vm.userData = jwt_decode(token);

        // gets all country and its states
        myService.getCountryDetails()
            .then(function(msg){
                vm.countries = msg.data;
            },function(errMsg){
                console.log(errMsg)
            });

        var paramData = {
            params : {
                id : vm.userData.id
            }
        };


       // gets user data 

        myService.getUserDetails(paramData)
            .then(function (msg) {
                vm.user = msg.data.map(function (obj) {
                    var rObj = {
                        name: obj.name,
                        email: obj.email,
                        country : obj.country.id,
                        state : obj.state.id
                    };
                    return rObj;
                })[0];
                // once user data is fetched it takes user country and then pass to filter function to get all its state
                vm.onCountryChange(vm.user.country.id)
            }, function (errMsg) {

            });
    }
    init();
}
})();

这里onCountryChange()似乎在它获得用户国家ID之前加载,优化我可以并行调用两个服务来获取数据,一旦请求完成并设置了用户对象,onCountryChange(countryId)可以触发以获取用户所属国家/地区的所有状态。

制作两个并行的http请求很有用吗?

如何确定所有请求何时完成,然后才调用第二个功能?

1 个答案:

答案 0 :(得分:2)

这里有两个选项(两个都可以):

选项1:构建一个在getUserDetails中调用myService .getCountryDetails.then的承诺链,然后您不必更改getUserDetails <的逻辑/ p>

选项2:使用Promise.all会将您的getCountryDetailsgetUserDetails转为并行,这样您就可以{{1}调用vm.onCountryChange(vm.user.country.id)而不是Promise.all(p1, p2).then