Question

I need to get all root folders of lists on current web, with shrepoint client object model.

I try to use this code, but i have error

var context = SP.ClientContext.get_current();
var lists = context.get_web().get_lists();
context.load(lists);
context.executeQueryAsync(function (sender, args) {
    var enumerator = lists.getEnumerator();
    while (enumerator.moveNext()) {
       var list = enumerator.get_current();
       var rootFolder = list.get_rootFolder();
       context.load(rootFolder, 'ServerRelativeUrl');
       context.executeQueryAsync(
       function (sender, args) {
           //error
           var url = rootFolder.get_serverRelativeUrl();
           console.log(url);
       },
       function (sender, args) {
           console.log('error');
       });
    }
},
function (sender, args) {
     console.log('error');
});

Thanks

Was it helpful?

Solution

This error occurs because List.RootFolder property has not been initialized since it was not requested.

In order to load List.RootFolder replace the line:

context.load(lists);

with this one:

context.load(lists,'Include(RootFolder)');

But the specified example contains another flaws:

  • Since SP.ClientContext.executeQueryAsync method is async and it is used in a loop, it will not print all folders as you expect it to
  • There is no need to perform a subsequent query for ServerRelativeUrl property

Below is demonstrated the fixed version that prints root folders for all lists:

var context = SP.ClientContext.get_current();
var lists = context.get_web().get_lists();
context.load(lists,'Include(RootFolder)');
context.executeQueryAsync(function () {
    var enumerator = lists.getEnumerator();
    while (enumerator.moveNext()) {
       var list = enumerator.get_current();
       var rootFolder = list.get_rootFolder();

       var url = rootFolder.get_serverRelativeUrl();
       console.log(url);

    }
},
function (sender, args) {
     console.log('error');
});   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top