Chuyển đến nội dung chính

第 2 課:事件循環與非同步模式

事件循環階段(計時器、掛起、輪詢、檢查、關閉)。微任務與巨集任務。 process.nextTick 與queueMicrotask 與setImmediate。回調、Promise、非同步/等待。 Promise.allSettled,Promise.any。

💻 程式設計 — 第 2 課 第 2 課:事件循環與非同步模式

Node.js 核心:從基礎到高級

第 1 部分:Node.js 內部結構

亞洲開發網

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。