YouTip LogoYouTip

Nodejs Callback

Node.js is a JavaScript runtime environment built on the Chrome V8 engine, which allows JavaScript to run on the server side, independent of the browser. One of Node.js's core features is its non-blocking I/O (Input/Output) model, which makes Node.js very suitable for handling high-concurrency network applications. The direct manifestation of Node.js asynchronous programming is the callback. !(#) In Node.js, a callback function is an asynchronous programming pattern used to handle I/O operations, such as file reading/writing, database interactions, network requests, etc. These operations often take a relatively long time. If a synchronous approach is used, it will block the execution of the entire program until the operation is complete. By using callback functions, Node.js can continue executing other code while an I/O operation is in progress. Once the I/O operation is complete, the callback function is then executed. Node.js is single-threaded, but it achieves asynchronous operations through an event-driven model and callback mechanisms. ### Use Cases * I/O operations like reading files, writing files, etc. * Handling network requests. * Database queries. For example, we can read a file while executing other commands. After the file reading is complete, the file content is returned as a parameter to the callback function. This way, there is no blocking or waiting for the file I/O operation during code execution. This significantly improves Node.js's performance, allowing it to handle a large number of concurrent requests. Callback functions generally appear as the last parameter of a function: function foo1(name, age, callback) { }function foo2(value, callback1, callback2) { } * * * ## Examples ### Blocking Code Example Create a file named `input.txt` with the following content: website address: www. Create a file named `main.js` with the following code: ## Example var fs = require("fs"); var data = fs.readFileSync('input.txt'); console.log(data.toString()); console.log("Program execution finished!"); The execution result of the above code is as follows: $ node main.js Official Website: www. Program execution finished! ### Non-Blocking Code Example Create a file named `input.txt` with the following content: website address: www. Create a file named `main.js` with the following code: ## Example var fs = require("fs"); fs.readFile('input.txt',function(err, data){ if(err)return console.error(err); console.log(data.toString()); }); console.log("Program execution finished!"); **Parameter Explanation**: * `err` is the error object, which will have a value if the read fails. * `data` is the content of the file that was read. The execution result of the above code is as follows: $ node main.js Program execution finished!Official Website: www. From the two examples above, we understand the difference between blocking and non-blocking calls: * The first example executes the program only after the file reading is complete. * In the second example, we don't need to wait for the file reading to finish. This allows us to execute the subsequent code while the file is being read, greatly improving the program's performance. Therefore, blocking executes sequentially, while non-blocking does not require sequential execution. So, if we need to process the parameters of a callback function, we must write the logic inside the callback function. * * * ## Callback Hell When multiple asynchronous operations need to be executed in sequence, callback functions can lead to code nesting, making the code difficult to read and maintain. ## Example fs.readFile('file1.txt','utf8',(err, data1)=>{ if(err){ console.error('Error reading file1:', err); return; } fs.readFile('file2.txt','utf8',(err, data2)=>{ if(err){ console.error('Error reading file2:', err); return; } fs.readFile('file3.txt','utf8',(err, data3)=>{ if(err){ console.error('Error reading file3:', err); return; } console.log('Data from all files:', data1, data2, data3); }); }); }); To improve code readability and maintainability, the following methods can be used: * **Promises**: Promises are a new asynchronous programming pattern that allows you to handle asynchronous operations in a chained manner, avoiding callback hell. * **async/await**: Based on Promises, `async/await` provides a way to write asynchronous code that looks more like synchronous code, making asynchronous code easier to understand and maintain. * **Event-Driven Programming**: Node.js also supports event-driven programming, handling asynchronous operations by listening to and emitting events. ### 1. Using async/await async/await is a syntactic sugar introduced in ES2017 that allows you to handle asynchronous operations more conveniently, avoiding callback hell. ## Example const fs = require('fs').promises; async function readFiles(){ try{ const data1 = await fs.readFile('file1.txt','utf8'); const data2 = await fs.readFile('file2.txt','utf8'); const data3 = await fs.readFile('file3.txt','utf8'); console.log('Data from all files:', data1, data2, data3); }catch(err){ console.error('Error reading files:', err); } } readFiles(); ### 2. Using Promises Promises are another way to handle asynchronous operations, allowing chained calls to the `then` method to avoid nested callbacks. ## Example const fs = require('fs').promises; fs.readFile('file1.txt','utf8') .then(data1 =>{ console.log('Data from file1:', data1); return fs.readFile('file2.txt','utf8'); }) .then(data2 =>{ console.log('Data from file2:', data2); return fs.readFile('file3.txt','utf8'); }) .then(data3 =>{ console.log('Data from file3:', data3); }) .catch(err =>{ console.error('Error reading files:', err); }); Callback functions are a fundamental way to handle asynchronous operations in Node.js. However, as application complexity increases, the callback hell problem becomes more apparent. By using async/await or Promises, you can significantly improve code readability and maintainability.
← Postgresql FunctionsPostgresql Privileges β†’