I am fairly new to javascript and have spent some time trying to understand callbacks as they relate to SharePoint's CSOM, but have had some issues.
Essentially, I am running a query to get a collection of list items, then for each of those items, requesting additional information in a query from SharePoint. The problem is that I would like to then compile all those individual requests together and essentially "return" them.
I have tried putting the essentials of my script below, any help understanding how to properly issue a callback in this structure would be appreciated:
function mainFunctionHere() {
...[pull up a collection of list items]...
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
var emailList = '';
function onQuerySucceeded() {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
appendUserInfo(oListItem.get_item('Name').get_lookupId(), addToEmailList) + '; ';
}
alert(emailList); //this is where I would like to return the full list, but obviously it is executing before any queries in appendUserInfo complete
}
function appendUserInfo(userId)
{
...[query siteUserInfoList for email info on the provided user id]...
context.load(items,'Include(EMail)');
context.executeQueryAsync(function(){
if(items.get_count() > 0) {
var item = items.itemAt(0);
emailString = item.get_fieldValues().EMail;
}
emailList += emailString + "; ";
alert(emailList);
}
);
}