I have been learning nodejs, and one thing that continues to boggle my mind is async programming that nodejs is built on. Maybe I am doing something wrong, but despite all my research I can't wrap my mind around how I should adapt to it coming from synchronous programming background. I would really appreciate if someone gave me a simple async example based on the below structure, given you want to call func2 from anywhere.
function1(){
var obj = function2();
console.log(obj); //"undefined".
}
function2(){
//do stuff with DB and get obj
console.log(obj); //logs obj.
return obj;
}
The problem I stumbled upon is that obj prints as undefined in func1, while func2 has no problems with it. When I nested the functions within each other it worked, leading me to believe that due to async nature of nodejs it proceeded to log in func1 before func2 was finished. Am I wrong with my assumptions?
What I struggle with in the above example, is how would I code the functions instead of nesting them within each other, so I can call func2 from several different functions at once. I've looked into callbacks but couldn't understand the examples given in various answers with a function inside a function.