Promise là object đại diện cho async operation, có 3 states không thể revert: pending → fulfilled/rejected.
- Microtask queue:
.then()callbacks được đặt vào microtask queue (ưu tiên cao hơn setTimeout), chạy sau synchronous code nhưng trước event loop phases. - Static methods quan trọng:
Promise.all([p1,p2])— chờ tất cả resolve, reject ngay khi 1 cái reject (fail-fast);Promise.allSettled([p1,p2])— chờ tất cả settle bất kể kết quả, trả về[{status, value/reason}]— dùng khi muốn biết kết quả từng cái;Promise.race([p1,p2])— resolve/reject theo cái đầu tiên settle (dùng cho timeout pattern);Promise.any([p1,p2])— resolve khi 1 cái fulfilled, reject chỉ khi tất cả reject. - Error handling chain: nếu không có
.catch(), unhandled rejection — Node.js 15+ crash process mặc định.Promise.resolve(value)tạo fulfilled promise ngay, hữu ích để normalize sync/async APIs. - Lưu ý: error swallowing trong
.then(onFulfilled)không có.catch()— luôn chain.catch()hoặc dùng try/catch với await.
A Promise is an object representing an async operation with 3 non-reversible states: pending → fulfilled/rejected.
- Microtask queue:
.then()callbacks are placed in the microtask queue (higher priority than setTimeout), running after synchronous code but before event loop phases. - Important static methods:
Promise.all([p1,p2])— waits for all to resolve, rejects immediately if any rejects (fail-fast);Promise.allSettled([p1,p2])— waits for all to settle regardless of result, returns[{status, value/reason}]— use when you want the result of each individual promise;Promise.race([p1,p2])— resolves/rejects with the first to settle (use for timeout patterns);Promise.any([p1,p2])— resolves when any one fulfills, rejects only when all reject. - Error handling: without a
.catch(), an unhandled rejection — Node.js 15+ crashes the process by default.Promise.resolve(value)creates an immediately fulfilled promise, useful for normalizing sync/async APIs.
Pitfall: error swallowing in .then(onFulfilled) without a .catch() — always chain .catch() or use try/catch with await.