Node.js 的异步编程模式是其核心特性之一,它使得非阻塞I/O操作成为可能,从而提高了应用的性能。本文将介绍 Node.js 中的几种常见的异步模式。
常见异步模式
- 回调函数 (Callbacks) 回调函数是最传统的异步模式,它允许异步操作完成后执行相应的回调函数。
fs.readFile('data.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log(data.toString());
});
- Promise Promise 是一种更现代的异步模式,它提供了更清晰、更易于管理的异步代码。
const fs = require('fs').promises;
async function readData() {
try {
const data = await fs.readFile('data.txt');
console.log(data.toString());
} catch (err) {
console.error(err);
}
}
- 异步函数 (Async/Await) Async/Await 是最新的异步模式,它让异步代码看起来像同步代码。
async function readData() {
const data = await fs.readFile('data.txt');
console.log(data.toString());
}
扩展阅读
想了解更多关于 Node.js 的内容,可以阅读 Node.js 官方文档。
Node.js