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?
()from fn2 in your first example. You are calling the function, not passing it.fn2()with justfn2in thefn1method call.fn2()will evaluate, logging "world", and then will returnundefinedwhich is passed as the callback forfn1fn1asynchronous? You don't have to use a callback if the function you're passing it to is synchronous. You can just call the second function after calling the first one.