使用then()调用另外两个函数:Error - 无法调用undefined的方法“then”

时间:2014-01-20 00:12:31

标签: javascript jquery angularjs jquery-deferred

基本上我有一个函数getUserInfo,它有一个函数可以返回服务中的可用和已分配的组。然后我有下面的其他两个函数返回那些对象。但是,在第一个函数完成之前,我无法运行getAssignedGroups()getAvailableGroups()。所以我想我会使用then()来确保第一个函数完成后这两个运行。

我在控制器中有这个功能:

$scope.getUserInfo = function(selectedUser) {
    $scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups).then(
        $scope.assignedGroups = groupService.getAssignedGroups(),
        $scope.availableGroups = groupService.getAvailableGroups()
    );
};

这是我的服务:

spApp.factory('groupService', function () {
    var assignedGroups, availableGroups, allGroups;

    var getGroups = function () {
        allGroups = [];

        $().SPServices({
            operation: "GetGroupCollectionFromSite",
            completefunc: function(xData, Status) {
                var response = $(xData.responseXML);
                response.find("Group").each(function() {
                    allGroups.push({
                        id: $(this).attr('ID'),
                        name: $(this).attr('Name'),
                        Description: $(this).attr('Description'),
                        owner: $(this).attr('OwnerID'),
                        OwnerIsUser: $(this).attr('OwnerIsUser'),
                    });
                }); 
            }
        });
        return allGroups;
    }
    var getUserGroups = function (selectedUser, allGroups) {
        assignedGroups = [];

        $().SPServices({
            operation: "GetGroupCollectionFromUser",
            userLoginName: selectedUser,
            completefunc: function(xData, Status) {

                var response = $(xData.responseXML);

                response.find("errorstring").each(function() {
                    alert("User not found");
                    booErr = "true";
                    return;
                });

                response.find("Group").each(function() {
                    assignedGroups.push({                       
                        id: $(this).attr('ID'),
                        name: $(this).attr('Name'),
                        Description: $(this).attr('Description'),
                        owner: $(this).attr('OwnerID'),
                        OwnerIsUser: $(this).attr('OwnerIsUser'),
                    });

                });
            }
        });

        //from here I start comparing All Groups with user groups to return available groups
        var assignedGroupsIds = {};
        var groupsIds = {};
        var availableGroups = [];

        assignedGroups.forEach(function (el, i) {
            assignedGroupsIds[el.id] = assignedGroups[i];
        }); 

        allGroups.forEach(function (el, i) {
            groupsIds[el.id] = allGroups[i];
        });   

        for (var i in groupsIds) {
            if (!assignedGroupsIds.hasOwnProperty(i)) {
                availableGroups.push(groupsIds[i]);
            }
        }
/*      return {
            assignedGroups:assignedGroups,
            availableGroups:availableGroups
        }*/
    }
    var getAvailableGroups = function () {
        return availableGroups;
    }
    var getAssignedGroups = function () {
        return assignedGroups;
    };   

    return {
        getGroups:getGroups,
        getUserGroups:getUserGroups,
        getAvailableGroups: getAvailableGroups,
        getAssignedGroups:getAssignedGroups
    }
});

2 个答案:

答案 0 :(得分:0)

您可以将Angular promise模块注入您的工厂:

spApp.factory('groupService', function ($q) {

然后在工厂的getUserGroups()函数内,声明一个延迟对象:

var deferred = $q.defer();

然后,您需要在异步请求中使用deferred.resolve(response)并从您的函数返回deferred.promise。此外,then函数接受一个函数,返回的响应作为参数(这样您就可以从控制器访问响应):

$scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups).then(function(resp) {
    $scope.assignedGroups = groupService.getAssignedGroups(),
    $scope.availableGroups = groupService.getAvailableGroups()
});

查看AngularJS docs on $q以获取更多信息。

答案 1 :(得分:0)

更好的方法是使用回调方法。您可以采取以下方法。

$scope.getUserInfo = function(selectedUser, getUserInfoCallback) {
    $scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups, function (response){
        $scope.assignedGroups = groupService.getAssignedGroups( function (response){
        $scope.availableGroups = groupService.getAvailableGroups( function(response){
            //Here call parent callback
            if(getUserInfoCallback)
            {
                getUserInfoCallback(response); //If you need response back then you can pass it.
            }
        })
        })

    })    
    );
};

现在您需要将每个方法定义为回调。以下是供您参考的示例方法。

$scope.getAssignedGroups = function (getAssignedGroupsCallback){

//Do all operation
//Now call callback
if(getAssignedGroupsCallback)
{
getAssignedGroups();//you can pass data here which you would like to get it return
}

};

注意:我刚刚添加了代码以澄清方法。您需要更改它以编译和实现您自己的逻辑。

方法摘要:所有服务都是异步调用的,因此您需要将回调方法作为链传递(以保持代码清洁),以便您的代码可以等待下一步。

希望它有所帮助。