1. 事件循環階段
┌───────────────────────────┐
┌─>│ timers │ setTimeout, setInterval
│ └──────────┬────────────────┘
│ ┌──────────┴────────────────┐
│ │ pending callbacks │ I/O callbacks deferred
│ └──────────┬────────────────┘
│ ┌──────────┴────────────────┐
│ │ idle, prepare │ internal use
│ └──────────┬────────────────┘
│ ┌──────────┴────────────────┐
│ │ poll │ I/O events (fs, net)
│ └──────────┬────────────────┘
│ ┌──────────┴────────────────┐
│ │ check │ setImmediate
│ └──────────┬────────────────┘
│ ┌──────────┴────────────────┐
└──│ close callbacks │ socket.on('close')
└───────────────────────────┘
2. 微任務與巨集任務
console.log('1: Script start')
setTimeout(() => console.log('2: setTimeout'), 0) // Macrotask (timers)
setImmediate(() => console.log('3: setImmediate')) // Macrotask (check)
Promise.resolve().then(() => console.log('4: Promise')) // Microtask
queueMicrotask(() => console.log('5: queueMicrotask')) // Microtask
process.nextTick(() => console.log('6: nextTick')) // Microtask (ưu tiên cao nhất)
console.log('7: Script end')
// Output:
// 1: Script start
// 7: Script end
// 6: nextTick ← nextTick luôn chạy trước
// 4: Promise
// 5: queueMicrotask
// 2: setTimeout ← hoặc 3 trước (phụ thuộc event loop)
// 3: setImmediate
3. process.nextTick 與queueMicrotask
| 應用程式介面 | 佇列 | 訂單 | 何時使用 |
|---|---|---|---|
| process.nextTick | 下一個Tick隊列 | 最高 | 確保當前操作後立即運行 |
| 隊列微任務 | 微任務佇列 | 下一個Tick之後 | 符合標準、相容網絡 |
| 承諾然後 | 微任務佇列 | 下一個Tick之後 | 非同步連結 |
| 設定超時(fn, 0) | 定時器階段 | 巨集任務 | 延後到下一個事件循環迭代 |
| 設定立即 | 檢查階段 | 巨集任務 | I/O 輪詢後執行 |
4. 非同步模式的演變
import { readFile } from 'node:fs'
import { readFile as readFileAsync } from 'node:fs/promises'
// 1. Callback (old style)
readFile('/etc/hosts', 'utf8', (err, data) => {
if (err) throw err
console.log(data)
})
// 2. Promise
readFileAsync('/etc/hosts', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err))
// 3. Async/Await (recommended)
async function main() {
try {
const data = await readFileAsync('/etc/hosts', 'utf8')
console.log(data)
} catch (err) {
console.error(err)
}
}
5. Promise 組合器
const tasks = [
fetch('https://api.example.com/users'),
fetch('https://api.example.com/posts'),
fetch('https://api.example.com/comments'),
]
// Promise.all — fail nếu 1 reject
const [users, posts, comments] = await Promise.all(tasks)
// Promise.allSettled — không fail, trả status
const results = await Promise.allSettled(tasks)
results.forEach(r => {
if (r.status === 'fulfilled') console.log(r.value)
else console.error(r.reason)
})
// Promise.any — trả kết quả đầu tiên thành công
const fastest = await Promise.any(tasks)
// Promise.race — trả kết quả đầu tiên (fulfilled hoặc rejected)
const first = await Promise.race(tasks)
6. 中止控制器
const controller = new AbortController()
const { signal } = controller
// Timeout tự động cancel
setTimeout(() => controller.abort(), 5000)
try {
const response = await fetch('https://api.example.com/data', { signal })
const data = await response.json()
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
console.log('Request was aborted')
}
}
下一篇: 模組系統和套件管理 — CJS 與 ESM、npm、pnpm。