Skip to content

Instantly share code, notes, and snippets.

@martyglaubitz
Last active January 3, 2016 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martyglaubitz/8416815 to your computer and use it in GitHub Desktop.
Save martyglaubitz/8416815 to your computer and use it in GitHub Desktop.
A leaner version of the "executeQueryAsync" method of the ClientContext class
/*
* USAGE
*
* var ctx = SP.ClientContext.get_current();
*
* var web = ctx.get_web();
* var groups = web.get_siteGroups();
*
* ctx.loadAsync([web, groups], function (err, clientObjects) {
* if (err) {
* // do something about it
* }
*
* console.log('Site "' + web.get_title() + '" has ' + groups.get_count() + ' groups');
* });
*
* // query strings only work for collections up to now...
* ctx.loadAsync(groups, 'Include(Id, Title)',function (err, clientObjects) {
* ...
* });
*/
SP.ClientContext.prototype.loadAsync = function() {
var object = arguments[0];
var queryString;
var callback;
var that = this;
function load(object, queryString) {
if (queryString) {
that.load(object, queryString);
}
else {
that.load(object);
}
}
if (typeof arguments[1] === 'string') {
queryString = arguments[1];
callback = arguments[2];
}
else {
queryString = null;
callback = arguments[1];
}
if (object instanceof Array) {
for (var i = 0, len = object.length; i < len; i++) {
load(object[i], queryString);
}
}
else {
load(object, queryString);
}
if (!callback) {
return function(loadCallback) {
that.executeQueryAsync(function() {
loadCallback(null, object);
},
function(sender, args) {
loadCallback(args);
});
};
}
this.executeQueryAsync(function() {
callback(null, object);
},
function(sender, args) {
callback(args);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment