JavaScript 以單執行緒事件循環實現非阻塞 I/O,這是其併發模型的核心。理解同步/非同步邊界、事件循環階段、微任務隊列,是寫出高效、無 Bug 非同步代碼的前提。
┌─────────────────────────────────────────────────────────┐
│ Event Loop Tick │
├─────────────────────────────────────────────────────────┤
│ 1. 執行一個宏任務 (Macrotask) │
│ ├─ setTimeout / setInterval / setImmediate / I/O │
│ ├─ UI Rendering │
│ └─ script (整個 .js 檔案) │
├─────────────────────────────────────────────────────────┤
│ 2. 清空所有微任務 (Microtask) │
│ ├─ Promise.then / catch / finally │
│ ├─ queueMicrotask │
│ ├─ MutationObserver │
│ └─ process.nextTick (Node.js) │
├─────────────────────────────────────────────────────────┤
│ 3. UI Render (瀏覽器) │
└─────────────────────────────────────────────────────────┘
↓ 重複上述循環
console.log('a');
setTimeout(() => console.log('c'), 500);
setTimeout(() => console.log('d'), 500);
setTimeout(() => console.log('e'), 500);
console.log('b');
// 輸出: a, b, (500ms後) c, d, e(順序保證,但時間不精確)
var data;
$.ajax({url: '/api', success: d => data = d});
console.log(data); // undefined!AJAX 尚未完成
// 回調
$.ajax({url: '/api', success: data => console.log(data)});
// Promise (jQuery 3+ 返回 Promise)
$.ajax({url: '/api'}).then(data => console.log(data));
// async/await
async function fetchData() {
const data = await $.ajax({url: '/api'});
console.log(data);
}
fs.exists('file', exists => {
if (exists) fs.readFile('file', 'utf8', (err, content) => {
content = transform(content);
fs.writeFile('file', content, err => {
console.log('Done');
});
});
});
function onWrite(err) { console.log('Done'); }
function onRead(err, content) { fs.writeFile('file', transform(content), onWrite); }
function onExists(exists) { if (exists) fs.readFile('file', 'utf8', onRead); }
fs.exists('file', onExists);
const fs = require('fs').promises;
fs.access('file')
.then(() => fs.readFile('file', 'utf8'))
.then(content => fs.writeFile('file', transform(content)))
.then(() => console.log('Done'))
.catch(err => console.error(err));
async function processFile() {
try {
await fs.access('file');
const content = await fs.readFile('file', 'utf8');
await fs.writeFile('file', transform(content));
console.log('Done');
} catch (err) { console.error(err); }
}
const [users, posts, comments] = await Promise.all([
fetch('/users').then(r => r.json()),
fetch('/posts').then(r => r.json()),
fetch('/comments').then(r => r.json())
]);
import pLimit from 'p-limit';
const limit = pLimit(3); // 同時最多 3 個
const tasks = urls.map(url => limit(() => fetch(url).then(r => r.json())));
const results = await Promise.all(tasks);
for (const url of urls) {
const data = await fetch(url).then(r => r.json());
process(data);
}
const timeout = (ms) => new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
);
const data = await Promise.race([fetch('/api'), timeout(3000)]);
async、p-limit、bluebird 提供豐富併發控制JavaScript 非同步編程的本質是「將延遲操作排入隊列,主執行緒持續推進」。掌握事件循環微/宏任務機制,善用 Promise 鏈式組合與 async/await 語法糖,配合並行控制策略,即可寫出高併發、低延遲、易維護的非同步代碼。記住:沒有糟糕的語言,只有糟糕的程式設計師——善用工具,驾驭非同步。