I write a function to check if user in sharepoint group in javascript
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); currentContext.load(allGroups, 'Include(Users)'); currentContext.executeQueryAsync(OnSuccess, OnFailure); function OnSuccess(sender, args) { var userInGroup = false; var groupEnumerator = allGroups.getEnumerator(); while (groupEnumerator.moveNext()) { var oGroup = groupEnumerator.get_current(); if (groupName == oGroup.get_title()) { var allUsers = oGroup.get_users(); var userEnumerator = allUsers.getEnumerator(); while (userEnumerator.moveNext()) { var oUser = userEnumerator.get_current(); if (oUser.get_id() == currentUser.get_id()) { userInGroup = true; break; } } } } OnComplete(userInGroup); } function OnFailure(sender, args) { OnComplete(false); } }
I use it in another function, wish to get the bool value of OnComplete and return it.
function SetButtonPermission() { var isInGroup; IsCurrentUserMemberOfGroup("Global", function(isCurrentUserInGroup) { isInGroup = isCurrentUserInGroup; }); return isInGroup; }
It seems like I cannot get the bool isCurrentUserInGroup because it alert "isInGroup is undetified". So How Can I Get The bool value ?
Similar to the answer provided here, when you're dealing with asynchronous function calls and callbacks, you'll be better off injecting data/logic into your callback function instead of returning data out from it.
The alternative is to push the "return" data into a global variable, or at least to a variable accessible within the same scope as the callback's execution, and delay execution of dependent logic until after the callback has executed.
You might want to look into JavaScript promises to see how script authors typically handle asynchronous code.