Node.js là nền tảng xử lý đơn luồng, nhưng lại có khả năng xử lý nhiều tác vụ đồng thời nhờ vào cơ chế bất đồng bộ (asynchronous). Dưới đây là những cách xử lý bất đồng bộ phổ biến:
1. Callback
// Đọc file sử dụng callback
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Lỗi khi đọc file:', err);
return;
}
console.log('Nội dung file:', data);
});
console.log('Đang đọc file...');
2. Promise
// Đọc file sử dụng Promise
const fs = require('fs').promises;
fs.readFile('data.txt', 'utf8')
.then(data => {
console.log('Nội dung file:', data);
})
.catch(err => {
console.error('Lỗi khi đọc file:', err);
});
console.log('Đang đọc file...');
3. Async/Await
// Đọc file sử dụng async/await
const fs = require('fs').promises;
async function readFileData() {
try {
const data = await fs.readFile('data.txt', 'utf8');
console.log('Nội dung file:', data);
} catch (err) {
console.error('Lỗi khi đọc file:', err);
}
}
readFileData();
console.log('Bắt đầu đọc file...');
Ví dụ thực tế: API lấy dữ liệu từ database
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
// Khởi tạo kết nối database
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
// API lấy danh sách sản phẩm
app.get('/products', async (req, res) => {
try {
// Kết nối database và query dữ liệu
const [rows] = await pool.query('SELECT * FROM products');
// Xử lý dữ liệu trước khi trả về
const products = rows.map(product => ({
id: product.id,
name: product.name,
price: product.price,
description: product.description
}));
// Trả về dữ liệu dạng JSON
res.json({
success: true,
data: products
});
} catch (error) {
console.error('Lỗi khi truy vấn database:', error);
res.status(500).json({
success: false,
message: 'Đã xảy ra lỗi khi lấy dữ liệu'
});
}
});
// Khởi động server
app.listen(3000, () => {
console.log('Server đang chạy tại http://localhost:3000');
});