Understanding Callbacks
Learn how callbacks work in Node.js and how they enable asynchronous programming.
Imagine you’re baking cookies. Once they’re in the oven, you need to take them out when they’re ready to prevent them from burning. Instead of waiting by the oven, you set a timer and use the time to handle other tasks. When the timer goes off, it reminds you to take out the cookies; this is the action that needs to happen after the timer completes.
In programming, callbacks are like the action of taking the cookies out. They define what needs to happen when an asynchronous task completes. The program, like the timer, can continue running other tasks in the meantime and execute the callback when it’s time to handle the result of the operation. This allows the program to remain efficient and responsive.
What is a callback?
A callback is simply a function passed as an argument to another function, intended to be executed once a specific operation is complete. Callbacks are especially useful for handling asynchronous tasks because they allow code to continue running without waiting.
We've already seen callbacks in action with setTimeout. Recall how setTimeout took a function as an argument and executed it after a delay, without pausing the rest of the code. Let’s now see how callbacks work in other scenarios, especially when handling tasks that take time, like reading and writing files.
Callbacks allow us to:
Run asynchronous tasks without blocking the main thread.
Respond to events, such as data loading or file operations, only after those tasks complete.
Improve efficiency by allowing code to continue executing other tasks without waiting.
Example: Reading a file with fs.readFile
The fs.readFile function lets us read a file asynchronously, allowing other operations to proceed while the file is being loaded. This function accepts three parameters:
File path: The name and path of the file to read.
Encoding: The character encoding for reading the file (e.g.,
'utf8').Callback function: A function with two parameters,
erroranddata, that handles the result of the read operation.
Let’s explore how fs.readFile uses callbacks to handle file reading asynchronously.