I'm just trying a simple callback to get code to execute in order instead of asynchronously. This does not work:
function fn1(string, func){
console.log("hello");
func();
};
function fn2(){
console.log("world");
}
fn1("meaninglessString", fn2());
It actually print "world" then "hello" to the console then crashes. But this does:
function fn1(string, func){
console.log("hello");
func();
};
fn1("meaninglessString", function(){
console.log("world");
});
Do I have to always write the callback function code right in the call to fn1 or is there a way to reference an already-written function? Also, is this the best way to be doing this in Node.js if I just want one function to happen after another has finished?
Take a look at your last line:
fn1("meaninglessString", fn2());
it should be the following instead:
fn1("meaninglessString", fn2);
Including the parenthesis causes fn2 to be executed immediately.
In your first block you have:
fn1("meaninglessString", fn2());
This says "call fn1 with arguments "meaninglessString" and the result of calling fn2 with no arguments". So the interpreter does that it calls fn2 and gets nothing in return from it, it prints "world" as a biproduct it then calls fn1 with the arguments "meaninglessString" and undefined which prints "hello" and calls a function that hasn't been set(undefined) hence it crashes.
If instead you change your code to pass the function rather than the result of calling the function as below it will work as you expected
function fn1(string, func){
console.log("hello");
func();
};
function fn2(){
console.log("world");
}
fn1("meaninglessString", fn2);