Solution: clientcontext.executequeryasync not working for Some Users

Total visits : 173

Issue: While executing Asynchronous call to get users list or any SharePoint lists data executequeryasync function not working for some users.

My requirement: When loading the page I need to get the user name and validate the user belongs to one of the group in SharePoint.

First I created a code based on Microsoft sample given in the MSDN, but it is working fine in my system but some of the machines not working


SP.SOD.executeOrDelayUntilScriptLoaded(validateUser, 'SP.js');

function validateUser()

{

clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
groupCollection = web.get_siteGroups();

user = web.get_currentUser(); //get the current user
clientContext.load(user);

group = groupCollection.getById(1);
groupUsers = group.get_users();
clientContext.load(group);
clientContext.load(groupUsers);

clientContext.executeQueryAsync(function()
{
//my code
}, 
function() 
{ 
//my failure code
}
);

}

Above code working fine for some users and not working for some users, after analysis I found the issue is that clientContext.load() will probably take a noticeable amount of time to execute, since it has to go to the SharePoint server and load data. Any time you have to go to SharePoint server things are going to be slow.

As we call the function async it moved to next step and throws error…

Solution:

Finally I have split the code into two executeQueryAsync method and solve the issue…

function validateUser()
{
clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
groupCollection = web.get_siteGroups();

user = web.get_currentUser(); //get the current user
clientContext.load(user);

clientContext.executeQueryAsync(getUserName, userfailure)
}

function getUserName()
{
$("#currentUserName").val(user.get_title());

group = groupCollection.getById(1);
groupUsers = group.get_users();
clientContext.load(group);
clientContext.load(groupUsers);

clientContext.executeQueryAsync(IsUserAdmin, userfailure)
}

function IsUserAdmin()
{
if (groupUsers.get_count() > 0)
{
for (var i = 0; i < groupUsers.get_count(); i++)
{
if (groupUsers.itemAt(i).get_loginName() == user.get_loginName())
{
$('#currentUserRole').val('admin')
break;
}
}
}

}

function userfailure()
{
//error message
}

Always think about the waiting time and proceed the asynchronous programming, we have another option using promise.

  • Sathish Nadarajan

    Nice article