async/await cho phép viết code bất đồng bộ trông như code tuần tự.
async function showOrderDetail(userId) {
const user = await getUser(userId); // chờ Promise, lấy giá trị
const orders = await getOrders(user);
return getDetails(orders[0]); // hàm async luôn trả về Promise
}
const fetchJson = async (url) => (await fetch(url)).json();
class Api {
async load() { /* method async */ }
}async luôn trả về Promise. return x → Promise fulfilled với x; throw e → Promise rejected với e.await tạm dừng hàm hiện tại (không chặn cả chương trình), phần còn lại chạy như một microtask khi Promise xong.async function saveProfile(data) {
try {
const res = await fetch("/api/profile", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (
IMPORTANT
fetch chỉ reject khi lỗi mạng. Mã 404 hay 500 vẫn là "thành công" về mặt Promise — luôn kiểm tra res.ok.
Trong ES module, có thể dùng await ngay ở cấp cao nhất:
const res = await fetch("/config.json");
export const config = await res.json();Module nào import file này sẽ chờ nó xong mới chạy.
const user = await getUser();
const products = await getProducts();
const banners = await getBanners();const [user, products, banners] = await Promise.all([
getUser(),
getProducts(),
getBanners(),
]);Chỉ await tuần tự khi bước sau cần kết quả của bước trước.
// SAI: forEach không chờ callback async — hàm in "xong" trước khi lưu xong
items.forEach(async (item) => await save(item));
console.log("xong");
// ĐÚNG: tuần tự
for (const item of items) await save(item);
// ĐÚNG: song song
await Promise.all
Comments