1

I'm trying to get all task items from all subsites of a SharePoint site and got stuck when trying to get all the responses into one global array for further processing. The array gets filled but when you try te get the element it shows undefined.

var TaskList = [];
$(document).ready(function() {
    Main();
});

function Main (){
    var SiteUrl = _spPageContextInfo.webAbsoluteUrl;
    var main = $("#main");

function GetListItems (TragetUrl){
        $.ajax({
        url: SiteUrl + "//" + TragetUrl + "/_api/web/lists/getbytitle('Tasker')/items?$select=Title,Status,StartDate,Status,DueDate",
        type: "GET",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.TestListItem' }}),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(d) {
            // TaskList.push(d.d.results)
            $.each(d.d.results, function(idx, Task){
                    console.log(Task['Title']);
                    TaskList.push(Task);
                });
            // return TaskList;
            },
        error: function() {console.log('failed to get');}
    });
}
function GetSubsites (BaseUrl){
    $.ajax({
        url: BaseUrl + "/_api/web/webs?$select=Title",
        type: "GET",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.WebCollection' }}),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(d) {
            console.table(d.d.results);
            //process Subsites
            $.each(d.d.results, function(idx, subsite){
                    console.log(subsite["Title"]);
                    GetListItems(subsite["Title"]);
                });
            },
        error: function() {console.log('fail');}
    }); 
}
    GetSubsites(SiteUrl);
    console.log(TaskList); //array output apears normal
    console.log(TaskList[0]); //undefined
    console.log(TaskList.length); // length is 0
}

Thanks.

AnatoliiV
  • 21
  • 4
  • `ajax` is asynchronous, meaning that it does not need to finish execution before the `console.log`s start. The reason that the array appears filled is that the `console.logs` are _also_ asynchronous, in that, when you log an object, they may print the object's state much later than when `console.log` was actually called (this is why `console.log(TaskList)` shows the filled array). Whereas trying to log `TaskList[0]` evaluates `TaskList[0]` _immediately_. You should be able to fix this by implementing proper asynchronous behavior using async/await / promises. – Ollin Boer Bohan Nov 10 '18 at 19:32
  • 1
    See [Is Chrome's javascript console lazy about evaluating arrays](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) for why you see the values of your array in the first console log – Patrick Evans Nov 10 '18 at 19:33
  • First of all, notice that your `GetSubsites()` is an asynchronous function. You're calling `console.log()` without waiting for its results. I'd assume that you can see the items in `console.log(TaskList)` because browser console evaluates the _objects_ in real time, not at the time of calling `console.log()`. So what you see is a reference to `TaskList`, which eventually gets populated by your async funtion. On the other hand, `console.log(TaskList[0])` prints out `undefined` because that's what it gets at the time of calling. Same thing with `TaskList.length` - it's 0 at the time of calling. – shkaper Nov 10 '18 at 19:34
  • @OllinBoerBohan, could you please show me an example on how to implement async/await in my code? – AnatoliiV Nov 10 '18 at 19:41
  • I read thru all the links and still I'm not able to do that. Coudl you show me a working exapmle? – AnatoliiV Nov 10 '18 at 22:22

0 Answers0