-1

I have an unusual problem and I can't determine why it's happening. I've created an object, and I update the values from within a loop. After this loop completes, I attempt to access a value which is undefined. I think this is simply best demonstrated by showing you my code. Can anyone help me to understand what's happening here?

function loadCounts() {

    var counts = {
        enroll: {},
        term: {},
        change: {}
    };

    var forms = [
        "enroll/pending",
        "enroll/approved",
        "term/pending",
        "term/approved",
        "change/pending",
        "change/approved",
    ];

    $.each(forms, function( index, value ) {

        if (!(value.split("/")[0] in counts)) {
            counts[value.split("/")[0]] = {};
        }

        $.ajax({
            url: apiURL+'/online/payroll/admin/dashboard/counts/'+value,
            headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('apiToken') },
            crossDomain: true,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                counts[value.split("/")[0]][value.split("/")[1]] = response.count;
            },
            error: function (XMLHttpRequest) {
                console.log("error", XMLHttpRequest)
            }
        });
    });

    console.log('count object:', counts)
    console.log('enroll object:', counts.enroll)
    console.log('pending count:', counts.enroll.pending)
}

loadCounts();

And the result in console:

enter image description here

Crayons
  • 1,906
  • 1
  • 14
  • 35
  • 2
    Counts will not be loaded by the time you do your console logging. As they are loaded with ajax, they will not be loaded until the success callback happens. This is entirely related to the duplicate. – Taplar May 02 '19 at 19:29
  • 3
    Seeing the results in the console is misleading, as browsers show objects in the console as they are up to date. Not as they were when they were originally logged. – Taplar May 02 '19 at 19:30

1 Answers1

-1

Your code is doing something async, so the calls to print might evaluate before your ajax requests return.

I can recommend watching this talk to get an intuitive understanding of what is happening here:

https://www.youtube.com/watch?v=8aGhZQkoFbQ

see also: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

reggaemuffin
  • 1,188
  • 2
  • 11
  • 26