How to read SharePoint lists data using CSOM

Spread the love

One simple way to read multiple lists within same web is to enumerate all lists and read data if your required list is found while enumeration.

For this, we need to use following piece of code:

var ctx = new SP.ClientContext.get_current();
var currweb = ctx.get_web();
var allLists = currweb.get_lists();
ctx.load(allLists, 'Include(Title, ItemCount, Description, DefaultDisplayFormUrl)');
ctx.executeQueryAsync(function () {
 var allEnum = allLists.getEnumerator();
 while (allEnum.moveNext()) {
  var oList = allEnum.get_current();
  var title = oList.get_title();
  if(title == "ListA" || title == "ListB" || title == "ListC") {
   //Perform your stuff
  }
 }
});

In above code, the only thing which bothers is that we are going through each and every list within the web to see if it is our required list or not. Imagine if we have dozens of lists and we only need to read data from few lists, let say 5 or 6 lists. Off course it is an overhead and can cause performance issues.

Recently I came across performance issue caused by iterating all lists and reading only few from them. So I thought of creating a solution which is faster.

The idea I implemented is to create an array of async calls and each async call will treat only one list.

var ReadMyLists = function () {
   var asyncCallbacks = [];
   var myLists = ['ListA','ListB','ListC'];
   for(var i = 0; i < myLists.length; i = i + 1) {
     asyncCallbacks.push(GetListData(myLists[i]));
   }
   $.when.apply($, asyncCallbacks).done(function() {
        //return from GetListData
   });   

}

Here is the function which reads a single list.

function GetListData(listName) {
 var d = $.Deferred();
 var ctx = new SP.ClientContext.get_current();
 var currweb = ctx.get_web();
 var oList = currweb.get_lists().getByTitle(listName);
 ctx.load(oList);
 ctx.executeQueryAsync(function () {
  //Do my stuff
  d.resolve();
 });
 return d.promise();
}

Using second method of iterating lists and reading their data, I gained more than 50% performance.