JavaScript Promises và Async/Await toàn tập
Từ Callback Hell đến Promise
Trước đây, code async thường rơi vào "callback hell":
getUser(id, (err, user) => {
if (err) return handleError(err);
getPosts(user.id, (err, posts) => {
if (err) return handleError(err);
getComments(posts[0].id, (err, comments) => {
// ... tiếp tục lồng sâu
});
});
});
Promise ra đời
getUser(id)
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log(comments))
.catch(handleError);
Async/Await - Đỉnh cao của sự sạch sẽ
async function fetchData(id) {
try {
const user = await getUser(id);
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
console.log(comments);
} catch (error) {
handleError(error);
}
}
Parallel Execution
// Chạy song song
const [user, posts] = await Promise.all([
getUser(id),
getPosts(id)
]);
Best Practices
- Luôn có
.catch()hoặctry/catch - Không mix callback và Promise
- Dùng
async/awaitcho readability - Xử lý error tập trung nếu có thể
Kết luận: Async/await là cách viết async code hiện đại nhất hiện nay.
