Khái niệm
Promise (ES2015) đại diện cho giá trị sẽ có trong tương lai (async operation). 3 trạng thái:
- Pending: Đang chờ
- Fulfilled/Resolved: Thành công, có value
- Rejected: Thất bại, có reason (error)
Ví dụ: Fetch users với Promise
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Promises</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample { font-size: 14px; font-weight: 500; color: #d32f2f; margin: 15px 0; padding: 15px; background: #ffebee; border-radius: 4px; max-height: 300px; overflow: auto; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
.loading { color: #1976d2; }
.error { color: #c62828; }
</style>
</head>
<body>
<h1>JavaScript Promises</h1>
<div class="sample" id="sample"></div>
<button id="btn">FETCH USERS (Promise)</button>
<h3>Nhấn nút để lấy danh sách user từ API</h3>
<script>
const sampleEle = document.getElementById('sample');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
sampleEle.textContent = 'Đang tải...';
sampleEle.className = 'sample loading';
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(users => {
sampleEle.className = 'sample';
sampleEle.innerHTML = users.map(u =>
`👤 ${u.name} (@${u.username}) - ${u.email}`
).join('
');
})
.catch(err => {
sampleEle.className = 'sample error';
sampleEle.textContent = `❌ Lỗi: ${err.message}`;
});
});
</script>
</body>