Previous Lecture Complete and continue  

  Callbacks and Their Conventions

So let's start with this problem. So we know Node.js, it's not blocking it's working asynchronously, so how can you schedule something in the future. For this we will use callback. So callbacks are just functions and as we know in JavaScript functions are first class citizens. So we can pass a callback like this. So we can pass a function t is a function, so we're just passing it as any other variable and then setTimeout we'll call that variable after one second, so 1,000 milliseconds it's one second. So that's very easy to understand when you think of a function just as any other variable as a number, as a string it's just value. There is nothing else to it.

And then under the hood setTimeout. It's implemented by the system. It's calling this function. Then we have a certain callback convention. This is fs. It's a file system module from nodejs. And the way it works, it's reading the data from a file. So the first argument data.csv, that's the file name then utf-8 it's some data and the callback is the last argument. So the first convention that is used a lot in nodejs is having a callback, having that function and the last argument, really calling a function. And then the second convention is the signature of the callback itself. It typically has at least two arguments error and data, so error would be the first argument and then the data would be the second argument. Even if you don't have an error you would still get a null after your first argument, so there would still be two arguments, at least two, maybe two or three or four arguments.

So this two conventions they are followed in the core Node.js modules, in most of the NPM modules. Of course it's not enforceable but it's very good to follow this when you're creating your own modules and obviously when you're consuming, that's what you need to use when you consuming these modules. But again Node.js is not enforcing it it's just a convention it's a style so we need to read the documentation on the source code. And the naming really doesn't matter what matters is the order.