如何从异步回调中返回一个布尔值

时间:2014-03-02 20:03:21

标签: javascript jquery

我需要知道用户是否在特定组中。 但我需要知道调用函数中的bool值。

我调试了下面的代码并且没问题,但是由于我不太了解js语法,我需要一些帮助。

我只需要将isCurrentUserInGroup设为true或false,这样我就可以进行进一步的比较。

var isCurrentUserInGroup= IsCurrentUserMemberOfGroup("Approvers");



    function IsCurrentUserMemberOfGroup(groupName, OnComplete) {

        var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();

        var currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);

        var allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);

        var group = allGroups.getByName(groupName);
        currentContext.load(group);

        var groupUsers = group.get_users();
        currentContext.load(groupUsers);

        currentContext.executeQueryAsync(OnSuccess,OnFailure);

        function OnSuccess(sender, args) {
            var userInGroup = false;
            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) {
                var groupUser = groupUserEnumerator.get_current();
                if (groupUser.get_id() == currentUser.get_id()) {
                    userInGroup = true;
                    break;
                }
            }  
            return userInGroup;
        }

        function OnFailure(sender, args) {
            return false;
        }    
    }

1 个答案:

答案 0 :(得分:2)

向“IsCurrentUserMemberOfGroup”功能添加回调。

IsCurrentUserMemberOfGroup("Approvers", function(isSuccess){
    // do what you want with "isSuccess"
});

function IsCurrentUserMemberOfGroup(groupName, callback) {

    var currentContext = new SP.ClientContext.get_current();
    var currentWeb = currentContext.get_web();

    var currentUser = currentContext.get_web().get_currentUser();
    currentContext.load(currentUser);

    var allGroups = currentWeb.get_siteGroups();
    currentContext.load(allGroups);

    var group = allGroups.getByName(groupName);
    currentContext.load(group);

    var groupUsers = group.get_users();
    currentContext.load(groupUsers);

    currentContext.executeQueryAsync(OnSuccess,OnFailure);

    function OnSuccess(sender, args) {
        var userInGroup = false;
        var groupUserEnumerator = groupUsers.getEnumerator();
        while (groupUserEnumerator.moveNext()) {
            var groupUser = groupUserEnumerator.get_current();
            if (groupUser.get_id() == currentUser.get_id()) {
                userInGroup = true;
                break;
            }
        }  
        callback(userInGroup);
    }

    function OnFailure(sender, args) {
        callback(false);
    }    
}