Search code examples
jquerysharepointdeferred

JQuery Deferred, Promises with SharePoint List


I'm running the following code to get SharePoint list items using JQuery Deferred/Promises to do something with that list. But when I run the code I get the error:

'The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'

Please find the code below:

$(document).ready(function () {
    //Do not execute jsom until sp.js file has loaded.
    ExecuteOrDelayUntilScriptLoaded(createGamesCloudDashboard, "sp.js");});
    //Function to retrieve Games Cloud Order Book from SharePoint server.
    function createGamesCloudDashboard() {
       getGamesCloudOrderBook().then(
         outputGamesCloudRevenue(gamesCloudItems),     
         function (sender, args) { 
           console.log('An error occurred while retrieving Games Cloud Order Books.')
         });
    }

   //CAML Query definition.
   function getGamesCloudOrderBook() {
       // Create Deferred object to run the consumer of 
       // the Games Cloud Order Book synchronously.
       var deferred = $.Deferred();
       var clContext = new SP.ClientContext('some url');
       var spList = clContext.get_web().get_lists().getByTitle('Name of List');   
       var gamesCloudOrderBook = new SP.CamlQuery();
       this.gamesCloudItems = spList.getItems(gamesCloudOrderBook);
       clContext.load(gamesCloudItems);
       clContext.executeQueryAsync(
         Function.createDelegate(this, 
           function () { deferred.resolve(gamesCloudItems) }),
         Function.createDelegate(this, 
           function (sender, args) { deferred.reject(sender, args) }));

       return deferred.promise();
   }

   function outputGamesCloudRevenue(gamesCloudItems) {
       //do something with the list.
   }

Solution

  • .then() expects named or anonymous function delegates as parameters.

    In the following piece of code...

    getGamesCloudOrderBook().then(
         outputGamesCloudRevenue(gamesCloudItems),     
         function (sender, args) { 
           ...        
        });
    

    ...you're not passing in the function outputGamesCloudRevenue as the first parameter, you're actually executing the function (with the undefined variable gamesCloudItems as its parameter) and then passing the executed function's return value (if any) to .then().

    Try this instead:

     getGamesCloudOrderBook().then(
         outputGamesCloudRevenue,     
         function (sender, args) { 
           console.log('An error occurred while retrieving Games Cloud Order Books.')
         });