async/await là syntactic sugar trên Promise — async function luôn return Promise, await pause execution của function đó (không block thread) cho đến khi Promise settle.
- Error handling: try/catch bắt rejected Promise như exception thông thường —
try { const data = await fetch(url).then(r => r.json()); } catch(e) { / network error, JSON parse error / }. - Parallel execution: sequential
await a(); await b()tổng thời gian = a + b; parallelconst [ra, rb] = await Promise.all([a(), b()])tổng thời gian = max(a, b). - Lưu ý #1 — sequential await trong loop:
for (const id of ids) { await fetchUser(id); }chạy tuần tự, chậm. - Fix:
await Promise.all(ids.map(id => fetchUser(id))). - Lưu ý #2 — error không được handle:
async function foo() { await riskyOp(); }gọifoo()mà không await/catch = unhandled rejection. - Top-level await: ESM modules hỗ trợ
awaitở top level (ngoài function) — hữu ích cho dynamic imports, DB init. - Khi debug: stack traces của async/await rõ ràng hơn Promise chains nhiều.