Question

I wrote the following code to break list item permission. Code works fine other than a small issue.

var user;
function breakItemPermission(itemID) {
    //Get the current context  
    var context = new SP.ClientContext();
    var oList = context.get_web().get_lists().getByTitle(listName);
    this.oListItem = oList.getItemById(itemID);
    oListItem.breakRoleInheritance(false);
    getCurrentUser();
    console.log(user);//undefined always
    var oUser = context.get_web().ensureUser(user);
    oListItem.get_roleAssignments().getByPrincipal(oUser).deleteObject();
    context.load(oUser);
    Id = itemID;
    context.load(oListItem);
    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    console.log('Role inheritance broken for item ');
    grantPermission(Id);
}

function onQueryFailed(sender, args) {
    grantPermission(Id);
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function getCurrentUser(){
    var context = new SP.ClientContext();
    currentUser = context.get_web().get_currentUser();
    context.load(currentUser);
    context.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceededGetCurrentUser), Function.createDelegate(this,this.onQueryFailedGetCurrentUser));
}

function onQuerySucceededGetCurrentUser() { 
    user=currentUser.get_email();
}

function onQueryFailedGetCurrentUser(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

In breakItemPermission() function user variable is always undefined even it's defined as global. Due to that current user permission cannot be broken. Any hack to overcome this problem?

Was it helpful?

Solution

This is because your function getCurrentUser() has an async operation (executeQueryAsync). JS does not wait for it to complete and executes the next line i.e. console.log(user).

You need write the subsequent code from getCurrentUser() inside the function onQuerySucceededGetCurrentUser then only you will get the current user.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top