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:
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:
Please, do not copy the code above. I have wrote it just to illustrate problems and I am sure it won’t work.
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:
The magic is done within the methods GetGroups, GetTermSets and GetTerms. For example, the GetGroups method could look like:
In order to see how you share information between methods, we could look at the GetTermSets method
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.