Skip to main content
Source Link
M_66
  • 103
  • 3

How do I define assign the results of an ajax call to an object property using defineProperty?

I am trying to assign the results of an ajax call to an object property that I created using the JavaScript defineProperty method.

var myArray = getArrayOfListsForObjects(); //returns an array of list names
var myBook = {};

//below defining a property of the book object using the name of
//the first list in the array myArray, and then try to set the value
//using an AJAX call
Object.defineProperty(TheBook,myArray[1].list,{
    value:clientContext.executeQueryAsync(getDetails(myArray[1],_onQueryFailed)),
    writable:true,
    enumerable:true,
    configurable:true
});

My function to get the list data:

function getDetails(listItem){
    var baseURL = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listItem.list +
    "?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages";

    $.ajax({
        url: baseURL,
        type: "GET",
        headers:{
          "accept":"application/json;odata=verbose",
        } 
    })
    .done(function(results){
        return results;
    })
}

I know that I am getting the correct results, but I'm not sure how I can assign them to object property. I've read enough to know that it has to do with the asynchronous nature or AJAX and that the script keeps loading even though all the results haven't been returned. I'm guessing I need some callback, but, unable to get my head around it at this time. Any help would be appreciated.