1

I am trying to simply add some objects from this callback function to a global array for use later. I am running into an issue with the asynchronous nature of the code and I don't understand why it isn't working.

For both arrays dl and arr, I cannot access their indices and the console claims their length is 0. However, in chrome dev-tools I can view a dropdown of about 1000 objects in the array, as should be the case.

dl[0] or arr[0] returns undefined, for example.

I should mention this is all within a componentDidMount() in my React app. The reason I am making arrays, as opposed to just setting state is that the function is embedded and within a get method here and the indices need to be accesed later anyhow.

let dl =[];
let arr=[];

_globalobject.get(
    "/SOME/URL.PARAMETERS/HERE",
    function(response) {
        // authenticated user
        _globalobject.user = response;
        for (let i=0; i < response.results.length; i++) {
            dl.push(response.results[i])
            arr.push(i)
        }
    }
)
console.log(dl, typeof(dl), dl.length) // [] > , 'object', 0
console.log("regular array", arr[0]) // regular array, undefined
clayton groth
  • 149
  • 1
  • 9

1 Answers1

0

The global arrays arr and dl will only be populated with data after the callback that you're passing to _globalobject.get() is called.

Currently, logging to console via console.log() occurs immediately (ie, before the callback is executed), which is why the arrays are reported empty via the console.

Try moving the console.log calls to the end of your callback function so that logging occurs when the arrays are populated with data, like so:

let dl =[];
let arr=[];

_globalobject.get(
    "/SOME/URL.PARAMETERS/HERE",
    function(response) {
        // authenticated user
        _globalobject.user = response;
        for (let i=0; i < response.results.length; i++) {
            dl.push(response.results[i])
            arr.push(i)
        }

        // Log to console, when the callback is executed. There
        // should now be data in these arrays, which will cause
        // the console to log expected output
        console.log(dl, typeof(dl), dl.length) // [] > , 'object', 0
        console.log("regular array", arr[0]) // regular array, undefined
    }
)
Dacre Denny
  • 26,362
  • 5
  • 28
  • 48
  • Good. I suspected something like this. Well. That makes things difficult because I still have to find a way to bind this embedded function.... – clayton groth Nov 05 '18 at 19:43
  • You're welcome - is there anything else I can help with? How do you need to bind the function? – Dacre Denny Nov 05 '18 at 19:48