SharePoint APIs have been dramatically improved over the last few years, especially when it comes to javascript but, even with those improvements, it’s sometimes very hard for developers with backend background to achieve goals that initially seem simple. To the fact that we don’t have (or we don’t know how to use) good development tools to help us with developing and debugging javascript code, we need to add the way you normally interact with SharePoint objects. Let me show you this with an example:
Imagine I want to show a list with elements coming from a taxonomy termset. Basically I would like to be able to query the site collection default term store and, by calling a method passing the name of the termset containing the items, retrieve the list of terms, iterate through them and fill my html control. To make it a little more complex, imagine we have actually two different html controls to fill with two different termset terms.
The first problem you are going to face when trying to implement the scenario above is the fact that SharePoint doesn’t provide you a method to retrieve the terms of a termset of the default group of the site collection’s default termstore. You will need to make a list of request to get the data, starting with this:
- var getGroups = function () {
- var clientContext = SP.ClientContext.get_current();
- var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
- var termStore = taxSession.getDefaultSiteCollectionTermStore();
- var groups = termStore.get_groups();
- clientContext.load(groups);
- clientContext.executeQueryAsync(function () {
- // Add here code to execute when groups are loaded
- }, function (sender, args) {
- console.log(args.get_message());
- });
- }
Then, in line 11 you will need to iterate through the list of groups to search the one you are looking for. In the case we are working on we are selecting the site collection’s default group. Once we have it, we will need to create a new request to get the list of termsets included in the selected group and after that, a new request for getting the list of terms on those termsets we are interested in. You will easily end up with something like:
- var getGroups = function () {
- var clientContext = SP.ClientContext.get_current();
- var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
- var termStore = taxSession.getDefaultSiteCollectionTermStore();
- var groups = termStore.get_groups();
- clientContext.load(groups);
- clientContext.executeQueryAsync(function () {
- var groupsEnum = groups.getEnumerator();
- while (groupsEnum.moveNext()) {
- var currentGroup = groupsEnum.get_current();
- if (currentGroup.get_isSiteCollectionGroup()) {
- var groupName = currentGroup.get_name();
- var termSets = currentGroup.get_termSets();
- var clientContext = SP.ClientContext.get_current();
- clientContext.load(termSets);
- clientContext.executeQueryAsync(function () {
- var clientContext = SP.ClientContext.get_current();
- var termSetsEnumerator = termSets.getEnumerator();
- while (termSetsEnumerator.moveNext()) {
- var currentTermSet = termSetsEnumerator.get_current();
- var termSetName = currentTermSet.get_name();
- if (termSetName === "field1" || termSetName === "field2") {
- var terms = currentTermSet.getAllTerms();
- clientContext.load(terms);
- clientContext.executeQueryAsync(function () {
- // Fill your controls here…
- }, function (sender, args) {
- console.log(args.get_message());
- });
- }
- }
- }, function (sender, args) {
- console.log(args.get_message());
- });
- break;
- }
- }
- }, function (sender, args) {
- console.log(args.get_message());
- });
- }
Please, do not copy the code above. I have wrote it just to illustrate problems and I am sure it won’t work.
What I wanted to highlight with the previous example is the typical problems you are going to face if you follow a similar approach. The first and most obvious is the spaguetti code syndrome. Yes, you are right, this can be easily fixed using delegate functions instead of nesting calls but you are going to face then some problems with the scope of variables and functions’ returned objects. Those that, like me, are not experts on javascript, will finish declaring everything globally and then you are on your own. Good luck! In addition, you must take into consideration that the subsequent calls will be queued and executed in a way that is not probably the one you are expecting. Again, problems, waste of time and frustration.
Promises
So, is there any way to make this process easier? One possible answer is “use promises”. The basic idea is that you can work with functions in a similar way of how you would work in synchronous development. The main function of the example above could be something similar to this:
- var p = getGroups();
- p.done(function (result) {
- var p2 = getTermSets(result);
- p2.done(function (result) {
- var p3 = getTerms(result, "field1");
- p3.done(function (result) {
- // Fill your control here
- });
- p3.fail(function (result) {
- console.log(result);
- });
- p3 = getTerms(result, "field2");
- p3.done(function (result) {
- // Fill your control here
- });
- p3.fail(function (result) {
- console.log(result);
- });
- });
- p2.fail(function (result) {
- console.log(result);
- });
- });
- p.fail(function (result) {
- console.log(result);
- });
The magic is done within the methods GetGroups, GetTermSets and GetTerms. For example, the GetGroups method could look like:
- var getGroups = function () {
- var d = $.Deferred();
- var clientContext = SP.ClientContext.get_current();
- var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
- var termStore = taxSession.getDefaultSiteCollectionTermStore();
- var groups = termStore.get_groups();
- clientContext.load(groups);
- var o = { d: d, groups: groups };
- clientContext.executeQueryAsync(
- Function.createDelegate(o, this.getGroupsCallback),
- Function.createDelegate(o, this.failCallback)
- );
- return d.promise();
- }
- var getGroupsCallback = function () {
- this.d.resolve(this.groups);
- }
- var failCallback = function () {
- this.d.reject("something bad happened");
- }
In order to see how you share information between methods, we could look at the GetTermSets method
- var getTermSets = function (_groups) {
- var d = $.Deferred();
- var clientContext = SP.ClientContext.get_current();
- var groupsEnum = _groups.getEnumerator();
- while (groupsEnum.moveNext()) {
- var currentGroup = groupsEnum.get_current();
- if (currentGroup.get_isSiteCollectionGroup()) {
- var groupName = currentGroup.get_name();
- var termSets = currentGroup.get_termSets();
- clientContext.load(termSets);
- var o = { d: d, termSets: termSets };
- clientContext.executeQueryAsync(
- Function.createDelegate(o, this.getTermSetsCallback),
- Function.createDelegate(o, this.failCallback)
- );
- return d.promise();
- break;
- }
- }
- }
As you have probably seen, the final result is really cleaner and easy to follow and you won’t need to deal with global variables because you can easily send parameters to functions and retrieve returning values.
For those of you who are still reading, I need to clarify something. If you search for “Promises” and “Javascript” you will find that I’m not actually using the cool new feature natively supported by some browsers. I’m using the implementation of this pattern included in jquery called Deferred. If you want to learn more about this topic, I recommend you visiting http://www.html5rocks.com/en/tutorials/es6/promises/