萬盛學電腦網

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

JavaScript 非同步回調函式執行順序控制:從回調地獄到 Async/Await

JavaScript 單執行緒非同步特性導致回調函式執行順序不可預測。本文系統解析順序控制演進:回調傳遞 → Promise 鏈 → Async/Await,並提供實務模式。

問題場景

// 需求:B 必須在 A 完成後執行
function A(callback) { asyncOp(param1, param2, callback); }
function B(callback) { asyncOp(param3, param4, callback); }

// ❌ 錯誤:平行執行,順序不保證
A(() => console.log('A done'));
B(() => console.log('B done'));

// 輸出可能:B done → A done

方案一:回調地獄

A(() => {
    console.log('A done');
    B(() => {
        console.log('B done');
        C(() => {
            console.log('C done');
            // 深層嵌套,難以維護、錯誤處理分散
        });
    });
});

方案二:Promise 鏈

// 將回調函式 Promise 化
function A_p() { return new Promise(resolve => A(resolve)); }
function B_p() { return new Promise(resolve => B(resolve)); }

A_p()
    .then(() => { console.log('A done'); return B_p(); })
    .then(() => { console.log('B done'); return C_p(); })
    .then(() => { console.log('C done'); })
    .catch(err => console.error('失敗:', err));

方案三:Async/Await(現代標準,推薦)

async function runSequence() {
    try {
        await A_p(); console.log('A done');
        await B_p(); console.log('B done');
        await C_p(); console.log('C done');
    } catch (err) {
        console.error('流程中斷:', err);
    }
}

runSequence();

進階控制模式

平行執行 + 等待全部完成

async function parallelAll() {
    const [resultA, resultB, resultC] = await Promise.all([
        A_p(), B_p(), C_p()
    ]);
    return { resultA, resultB, resultC };
}

平行執行 + 率先完成

async function race() {
    const winner = await Promise.race([
        A_p().then(r => ({task: 'A', result: r})),
        B_p().then(r => ({task: 'B', result: r})),
        timeout(5000).then(() => { throw new Error('逾時'); })
    ]);
    return winner;
}

順序執行但收集所有結果

async function sequentialCollect(tasks) {
    const results = [];
    for (const task of tasks) {
        results.push(await task());
    }
    return results;
}

// 使用
const tasks = [A_p, B_p, C_p];
const results = await sequentialCollect(tasks);

批次處理:限制併發數

async function batchWithConcurrency(tasks, concurrency = 3) {
    const results = [];
    const executing = [];
    
    for (const task of tasks) {
        const promise = task().then(result => {
            results.push(result);
            return result;
        });
        
        executing.push(promise);
        
        if (executing.length >= concurrency) {
            await Promise.race(executing);
            // 移除已完成的
            const completed = executing.findIndex(p => 
                // 簡易檢查,實際需用標記
            );
            executing.splice(0, 1);
        }
    }
    return Promise.all(executing).then(() => results);
}

// 更簡潔的併發控制庫:p-limit, bottleneck

JS 事件循環與微任務/巨任務

console.log('1. 同步開始');

setTimeout(() => console.log('2. setTimeout (巨任務)'), 0);

Promise.resolve().then(() => console.log('3. Promise.then (微任務)'));

queueMicrotask(() => console.log('4. queueMicrotask (微任務)'));

console.log('5. 同步結束');

// 輸出順序:
// 1. 同步開始
// 5. 同步結束
// 3. Promise.then (微任務)
// 4. queueMicrotask (微任務)
// 2. setTimeout (巨任務)

錯誤處理策略

// 策略一:全部成功才繼續(預設 Promise.all 行為)
await Promise.all([A_p(), B_p(), C_p()]);

// 策略二:全部完成再處理錯誤
const results = await Promise.allSettled([A_p(), B_p(), C_p()]);
results.forEach((r, i) => {
    if (r.status === 'fulfilled') console.log(`Task ${i}:`, r.value);
    else console.error(`Task ${i} 失敗:`, r.reason);
});

// 策略三:第一個失敗即停止(fail-fast)
for (const task of [A_p, B_p, C_p]) {
    await task(); // 拋出錯誤即中斷
}

實務建議

  1. 新專案預設用 Async/Await:可讀性最佳、除錯堆疊清晰
  2. 並行任務用 Promise.all/allSettled:不要用 forEach + await(會變順序執行)
  3. 錯誤邊界清晰:每個 await 區塊用 try/catch 或統一 .catch()
  4. 避免回調地獄:將舊式回調 API 用 Promise 包裝
  5. 取消機制:配合 AbortController 實作可取消的非同步操作

總結

非同步順序控制核心在於:將回調轉為 Promise,再用 Async/Await 線性表達順序邏輯。理解事件循環、微任務/巨任務優先級,能避免微妙的時序 Bug。現代 JS 開發應以 Async/Await 為主,輔以 Promise 靜態方法處理並行與競爭情境。

copyright © 萬盛學電腦網 all rights reserved