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.
async/await is syntactic sugar over Promises — an async function always returns a Promise; await pauses execution of that function (without blocking the thread) until the Promise settles.
- Error handling: try/catch catches rejected Promises like regular exceptions —
try { const data = await fetch(url).then(r => r.json()); } catch(e) { / network error, JSON parse error / }. - Parallel execution: sequential
await a(); await b()takes a + b total time; parallelconst [ra, rb] = await Promise.all([a(), b()])takes max(a, b) total time.
Pitfall #1 — sequential await in a loop: for (const id of ids) { await fetchUser(id); } runs one at a time.
Pitfall #2 — unhandled errors: async function foo() { await riskyOp(); } called as foo() without await/catch = unhandled rejection.