Trung BìnhNode.js iconNode.js

async/await trong Node.js là gì? Lợi ích so với Promise chains?

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; parallel const [ra, rb] = await Promise.all([a(), b()]) tổng thời gian = max(a, b).

Pitfall #1 — sequential await trong loop: for (const id of ids) { await fetchUser(id); } chạy tuần tự, chậm.

Pitfall #2 — error không được handle: async function foo() { await riskyOp(); } gọi foo() mà không await/catch = unhandled rejection.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js