What is Callback?
What is Callback?
A callback in Node.js is a function that is passed as an argument to another function and is executed after the completion of that function's task. This is a fundamental concept in Node.js, which is designed to perform asynchronous operations, allowing it to handle multiple operations concurrently without waiting for any single operation to complete.
In Node.js, callbacks are used extensively to handle asynchronous operations such as reading from a file, making HTTP requests, or querying a database. These operations can take an indeterminate amount of time to complete, and using callbacks ensures that the Node.js event loop is not blocked while waiting for these operations to finish. Instead, other operations can continue to run concurrently, which enhances the efficiency and scalability of applications.
When you pass a callback function to another function, Node.js will continue executing the rest of the program without waiting for the callback to be invoked. Once the asynchronous operation completes, the callback function is called with any resulting data or errors as arguments.
A common pattern in Node.js is the "error-first callback," where the first argument of the callback function is reserved for an error object. If the operation is successful, this argument is null or undefined. If an error occurs during the operation, the error is passed as the first argument, allowing the developer to handle it appropriately.
Here’s a simple example using the fs
module to read a file asynchronously:
const fs = require('fs');
fs.readFile('/path/to/file', (err, data) => {
if (err) {
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào