0

Made a new json object called new_week and initialized a new array inside. It prints fine right after initializing it but inside the callback function, it says it is undefined and throws an error when I try to push something (because it's undefined). Why is this?

    for(var i = 0; i < week_arr.length; i++){
        var new_week = {};
        new_week[week_arr[i]] = []
        console.log(new_week[week_arr[i]]); //prints []

        for(var j = 1; j < part_arr.length; j++){
            client.hgetall("xyz", function(err,object){
                console.log(new_week[week_arr[i]]); //prints undefined?
                new_week[week_arr[i]].push(something);   
            }
        }

}
shapiro
  • 131
  • 10
  • See http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript – Artyom Neustroev Feb 16 '16 at 19:12
  • 1
    Hope it also helps you to understand scopes and closures http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ – SiZE Feb 16 '16 at 19:16
  • So i could use a forEachloop for the inner loop but what if I wanted to start at index 1? – shapiro Feb 16 '16 at 20:48
  • If `function(err,object){` is an asynchronous call back it is because the for loop using counter `i` has completed leaving `i` set to `week_arr.length `. If so, search for "closure" and "loop counter" for existing answers. – traktor Feb 16 '16 at 21:00
  • okay thanks idk why callbacks are so complex. The "client.hgetall" is Redis db and is an async call. – shapiro Feb 16 '16 at 21:17
  • One more question I can't get my head around. I have an asynchronous function and I have an operation after that which relies on that async function to finish. How do I wait till the async function is done to process my next operation? – shapiro Feb 16 '16 at 23:39

0 Answers0