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.
You have to define functions (i.e. the callbacks) within functions.
function2
can be called from many places at once, not justfunction1
.If you can be more specific about what you don't understand, then you might get a better answer.
Functions are values, just like numbers, strings and objects.
This is the core fundamental of functional programming, and probably the thing you haven't grasped. In JavaScript, as in a number of languages, functions are not special*. This is different to languages like C or Java, where functions/methods are different to the usual values you deal with in your code.
So, we can declare functions and pass them around, separately to calling them. Now, what about the code we started with.
function1
that takes no argumentsfunction1
is called, callfunction2
with a single argument, a new nameless function that takes anobj
argumentconsole.log
with the value passed forobj
function2
that takes a single argumentcallbackFn
callbackFn
with a single argument, theobj
we got from somewhereSo the declaration order is 1, 4, 2; and the execution order is 2, 5, 3.
*OK, they're a little special. Their definitions are hoisted, you can execute the code they represent, and their declarations create scope and closures. But those are all questions for another time.