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 化
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 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
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(); // 拋出錯誤即中斷
}
非同步順序控制核心在於:將回調轉為 Promise,再用 Async/Await 線性表達順序邏輯。理解事件循環、微任務/巨任務優先級,能避免微妙的時序 Bug。現代 JS 開發應以 Async/Await 為主,輔以 Promise 靜態方法處理並行與競爭情境。