Ahhhh yes, that’s a confusing thing about callbacks. So, you know how you can do this:
somefunc(1, 2)
And that passes 1 and 2 to somefunc. You can also do this:
let x = 1;
let y = 2;
somefunc(x, y);
That assigns 1 to x and 2 to y, then calls somefunc with x and y. But, that ends up being the same as somefunc(1,2).
Alright, do you see how you’re doing this:
const print_lines = (err, data) => {
console.log(data.toString());
}
Welllll, you’re making a variable named print_lines and assigning a function to it. It’s just like let x = 1
, and there’s no reason to say that functions are now some kind of magic thing that can’t be like 1 or 2 or x or y. That means when you do this:
fs.readFile(“poem.txt”, print_lines);
You are passing the variable print_lines
to the fs.readFile
function. That. Is. All. Now, it just so happens that readFile expects this variable to be a function and not a number. When it gets a function it will call it for you.
When you write this:
fs.readFile(“poem.txt”, print_lines(err, data));
You are trying to call print_lines for the fs.readFile function, before you call readFile, but then also trying to use the err, and data variables that only fs.readFile knows about. You are basically trying to do fs.readFile’s job.
So, in callbacks treat functions like variables and let someone else call them. If you put () after your callback then you are telling javascript to call your callback right there, not later.