John Liu .NET

View Original

jQuery Promise syntax to wrap SharePoint SP.SOD

 

jQuery has a special function $.Deferred - which lets you create an Deferred object to build Promise(s).

We use this to simplify everything we do in SharePoint and other JavaScript libraries.

 

Wrapping SP.ClientContext

function GetCurrentUserName() {

var deferred = $.Deferred();
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var currentUser = web.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync( function(sender, args) {
    deferred.resolve();
}, function() {
    deferred.fail();
});

var promise = deferred.promise();
promise.done( function() {
    var title = currentUser.get_title();
});

return promise;
}

Wrapping SP.SOD

function SPLoaded() {

var deferred = $.Deferred();
SP.SOD.executeOrDelayUntilScriptLoaded( function() { deferred.resolve(); }, "sp.js");

return deferred.promise();

}

Resolving multiple promises

var promise1 = ...
var promise2 = ...
var promise3 = ...

$.when(promise1, promise2, promise3).done(function(){

// do something

});

 

Concatenating Arrays of promises

 

var promises = [];
promises.push(promise1);
promises.push(promise2);
...

// use this syntax when you don't know how many promises are there - may be calling REST in a loop.

return $.when.apply($, promises);

 

Combining Array of Promises and SP.SOD

 

function Ready() {

var promises = [];

var deferred1 = $.Deferred();
SP.SOD.executeOrDelayUntilScriptLoaded(deferred1.resolve, "sp.js");
promises.push(deferred1.promise());

var deferred2 = $.Deferred();
SP.SOD.executeOrDelayUntilScriptLoaded(deferred2.resolve, "sp.core.js");
promises.push(deferred2.promise());

 

return $.when.apply($, promises);

}

 

Combining promises

 

$(document).ready(function(){

    var vm = new ViewModel();  // not included in above script
    var promise = vm.Ready();
    promise.done( function() {
        vm.GetCurrentUserName();

    });

});

 

(Updated) And the grand finale

 

function Ready() {

var promises = [];

// using the special javascript argument "arguments"

$.each(arguments, function(index, arg) {
    var deferred = $.Deferred();
    SP.SOD.executeOrDelayUntilScriptLoaded(deferred.resolve, arg);
    promises.push(deferred.promise());
});

return $.when.apply($, promises);

}

 

$(document).ready(function(){

    var vm = new ViewModel();  // not included in above script
    var promise = vm.Ready("sp.js", "sp.core.js");
    promise.done( function() {
        vm.GetCurrentUserName();

    });

});