Câu hỏi phỏng vấn Nodejs
Câu hỏi

What is Callback?

Câu trả lời

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.

Definition and Usage

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.

How Callbacks Work

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.

Error Handling

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.

Example

Here’s a simple example using the fs module to read a file asynchronously:

javascript Copy
const fs = require('fs');

fs.readFile('/path/to/file', (err, data) => {
    if (err) {
    ...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

What are the Timing features of Node.js?

middle

What is the difference between browser global scope and Node.js global scope?

middle

What is the difference between require(x) and ES6 import x in Node.js?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào