Showing posts with label JSOM. Show all posts
Showing posts with label JSOM. Show all posts

Thursday, September 1, 2016

SharePoint JSOM : Alternative approach to nested executeQueryAsync with loops

Let’s assume that we need to get all pages in a site. Following are the steps we have to perform

  • Get all libraries
  • Get items in each library

Traditionally we would write a code like the below, but it will not provide expected response. This is due to the asynchronous nature of operations

Code that does not work

var context = SP.ClientContext.get_current();
var hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter("SPHostUrl")));

var web = hostContext.get_web();
var lists = web.get_lists();
context.load(lists);

context.executeQueryAsync(
function () {
    var listEnumerator = lists.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        if (oList.get_baseType() === 1) {

            var camlQuery = new SP.CamlQuery();
            var items = list.getItems(camlQuery);
            context.load(items);
            context.executeQueryAsync(
                function () {
                    var listEnumerator = lists.getEnumerator();

                }, function (sender, args) {
                    console.log('error!');
                });
        }
    }
}, function (sender, args) {
    console.log('error!');
});

As the solution, I broke the functionality in to two methods using Deferred objects. I’ve written a blogpost on Deferred objects and you can find it from here. Following is the preferred approach.

Working code with Deferred objects

function getSitePages()
{
    var context = SP.ClientContext.get_current();
    var hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter("SPHostUrl")));

    var web = hostContext.get_web();
    var lists = web.get_lists();
    context.load(lists);

    context.executeQueryAsync(
    function () {
        var listEnumerator = lists.getEnumerator();
        while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();
            if (oList.get_baseType() === 1) {

                var promise = getListItems(oList).then(function (state) {
                    console.log(state);
                });

            }

        }
    }, function (sender, args) {
        console.log('error!');
    });
}

function getListItems(list) {
    var dfd = $.Deferred();

    var context = SP.ClientContext.get_current();
    var hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter("SPHostUrl")));
           
    var camlQuery = new SP.CamlQuery();
    camlQuery.ViewFields = "<FieldRef Name='FileExtension' /><FieldRef Name='Title' />";
    camlQuery.set_viewXml("<View><Query><Where><Or><Contains><FieldRef Name='FileLeafRef' /><Value Type='Text'>.aspx</Value></Contains><Contains><FieldRef Name='FileLeafRef' /><Value Type='Text'>.html</Value></Contains></Or></Where></Query></View>");
    var items = list.getItems(camlQuery);
    context.load(items);

    context.executeQueryAsync(
        function () {
            var itemsCount = items.get_count();
            if (itemsCount > 0) {
                obj = {};
                obj.ListName = list.get_title();
                obj.ListPages = [];

                for (var i = 0; i < itemsCount; i++) {
                    var item = items.itemAt(i);
                    obj.ListPages.push(item.get_item('FileRef'));
                }

                dfd.resolve(obj);
            }
                   
        }, function (sender, args) {
            dfd.reject(sender, args, errorMsg);
        });

    return dfd.promise();
}

Sunday, June 21, 2015

How to use JQuery Deferred Objects in asynchronous operations for SharePoint JSOM

When we write SharePoint apps or client side logic in SharePoint pages, we may use asynchronous operations using JSOM or REST. As operations are asynchronous it is hard to control the flow of the execution. Apart from that we can make the situation even harder if we use nested asynchronous operations.

For an example I will read a web property using a REST call and the result is taken as an input to another REST call to read a list item.

Since my operations are asynchronous, how do I make sure that I enter to the second method once I return from the first method. It is difficult, right?

As a solution we can use JQuery Deferred objects. Following is a sample method to retrieve quick launch navigation links using deferred objects.

  1. function ReadNavigation() {
  2.     var def = $.Deferred();
  3.  
  4.     SP.SOD.executeOrDelayUntilScriptLoaded(function () {
  5.         var clientContext = new SP.ClientContext.get_current();
  6.         var quickLnch = clientContext.get_web().get_navigation().get_quickLaunch();
  7.         clientContext.load(quickLnch);
  8.  
  9.         clientContext.executeQueryAsync(
  10.             function () {
  11.                 var qlEnum = quickLnch.getEnumerator();
  12.                 var currentNav = [];
  13.                 while (qlEnum.moveNext()) {
  14.                     var node = qlEnum.get_current();
  15.                     var ob = {};
  16.                     var title = node.get_title();
  17.                     var url = node.get_url();
  18.  
  19.                     ob.title = title;
  20.                     ob.url = url;
  21.                     currentNav.push(ob);
  22.                 }
  23.                 def.resolve(currentNav);
  24.             }, function (sender, args) {
  25.                 def.reject("error");
  26.             });
  27.     }, "SP.js");
  28.     return def;
  29. }
  30.  
  31. ReadNavigation().done(function (nav) {
  32.     console.log(nav)
  33. }).fail(function (nav) { console.log("error!") })