Convert SharePoint JSOM's ExecuteQueryAsync to Promise in the Prototype
/Today's blog is about adding an additional method to SharePoint JavaScript Object Model (JSOM)'s ClientContext object, so we can use it directly like a promise.
I call it "executeQuery" (instead of executeQueryAsync)
Wrapper with jQuery's $.Deferred
SP.ClientContext.prototype.executeQuery = function() { var deferred = $.Deferred(); this.executeQueryAsync( function(){ deferred.resolve(arguments); }, function(){ deferred.reject(arguments); } ); return deferred.promise(); };
Wrapper with AngularJS's $q
SP.ClientContext.prototype.executeQuery = function() { var deferred = $q.defer(); this.executeQueryAsync( function(){ deferred.resolve(arguments); }, function(){ deferred.reject(arguments); } ); return deferred.promise; };
How do you use this?
var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); ctx.load(web); var promise = ctx.executeQuery(); // look! :-) promise.done(function(){ console.log(web.get_title()); }); promise.then(function(sArgs){ //sArgs[0] == success callback sender //sArgs[1] == success callback args }, function(fArgs){ //fArgs[0] == fail callback sender //fArgs[1] == fail callback args. //in JSOM the callback args aren't used much - //the only useful one is probably the get_message() //on the fail callback var failmessage = fArgs[1].get_message(); });
This may seem to be just small syntactic sugar, but now you have JSOM returning a promise that you can chain, loop, combine and juggle to your heart's content!
Remember, jQuery.ajax, SPServices, AngularJS, and now JSOM all returns promise objects now.