萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 同步與非同步機制深度解析:事件循環、Promise、async/await 與並行控制

前言:單執行緒的非同步藝術

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 (瀏覽器)                                    │
└─────────────────────────────────────────────────────────┘
        ↓ 重複上述循環

setTimeout / setInterval 非精確性


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(順序保證,但時間不精確)
  • HTML5 規範:巢狀 `setTimeout` ≥ 5 層時最小間隔 4ms
  • 主執行緒阻塞會延遲定時器觸發

AJAX 與 Promise 非同步流程

錯誤示範:同步思維寫非同步代碼


var data;
$.ajax({url: '/api', success: d => data = d});
console.log(data); // undefined!AJAX 尚未完成

正確模式:回調 / Promise / async-await


// 回調
$.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);

方案二:Promise 鏈式


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/await(最推薦)


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); }
}

並行控制模式

全並行:Promise.all


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())
]);

限制併發數:p-limit / 自實現


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...of + await


for (const url of urls) {
  const data = await fetch(url).then(r => r.json());
  process(data);
}

競速:Promise.race / Promise.any


const timeout = (ms) => new Promise((_, reject) => 
  setTimeout(() => reject(new Error('Timeout')), ms)
);
const data = await Promise.race([fetch('/api'), timeout(3000)]);

Node.js 非同步陷阱

  • 未處理的 Promise Rejection:Node 15+ 預設拋出錯誤,務必全域監聽或 `.catch()`
  • 頂層 await:僅在 ES Module (`.mjs` 或 `"type": "module"`) 可用
  • 流程控制庫:async、p-limit、bluebird 提供豐富併發控制

效能優化建議

  1. 避免順序執行可並行的任務:識別無依賴關係的 I/O,用 `Promise.all` 並行
  2. 複用連線:HTTP Keep-Alive、連線池、gRPC
  3. 背壓控制:生產者過快時暫停(Stream `pipe`、Transform 流)
  4. 取消機制:`AbortController` 配合 `fetch`、自定義取消令牌

總結

JavaScript 非同步編程的本質是「將延遲操作排入隊列,主執行緒持續推進」。掌握事件循環微/宏任務機制,善用 Promise 鏈式組合與 async/await 語法糖,配合並行控制策略,即可寫出高併發、低延遲、易維護的非同步代碼。記住:沒有糟糕的語言,只有糟糕的程式設計師——善用工具,驾驭非同步。

copyright © 萬盛學電腦網 all rights reserved