用一句話說明:將函式 B 作為參數傳給函式 A,A 執行完畢後再呼叫 B。這讓 A 的行為可被外部動態定製,而非寫死在 A 內部。
function main(callback) {
console.log('1. 主流程開始');
console.log('2. 主流程結束,準備呼叫回調');
callback(); // 執行傳入的函式
}
function sayHello() { console.log('→ 回調:Hello!'); }
function sayBye() { console.log('→ 回調:Goodbye!'); }
main(sayHello); // 輸出 1, 2, Hello!
main(sayBye); // 輸出 1, 2, Goodbye!
main 不需知道具體呼叫哪個函式,只關心「執行完後做什麼」。main 可搭配不同回調處理不同業務(成功/失敗、不同資料來源)。setTimeout、事件監聽、Promise 則是回調的典型應用場景。function fetchData(url, onSuccess, onError) {
// 模擬非同步
setTimeout(function() {
if (url) onSuccess({ data: '資料內容' });
else onError(new Error('URL 為空'));
}, 500);
}
fetchData('/api/users',
function(res) { console.log('成功:', res.data); },
function(err) { console.error('失敗:', err.message); }
);
| 陷阱 | 說明 | 解法 |
|---|---|---|
| 回調地獄 | 多層巢狀回調導致程式碼難維護 | 使用 Promise / async-await 扁平化流程 |
| this 丟失 | 回調內 this 指向錯誤 | 箭頭函式 / .bind(this) / 存儲 const self = this |
| 重複呼叫 | 非同步流程意外觸發多次回調 | 加旗標 let called = false 或使用一次性 Promise |
| 錯誤吞沒 | 回調拋錯未被捕獲 | 統一 try-catch 或 Promise .catch() |
// 回調風格
readFile('a.txt', function(err, a) {
readFile('b.txt', function(err, b) {
readFile('c.txt', function(err, c) { console.log(a+b+c); });
});
});
// Promise 鏈
readFileP('a.txt').then(a => readFileP('b.txt')).then(b => readFileP('c.txt')).then(c => console.log(c));
// async/await(推薦)
async function loadAll() {
const a = await readFileP('a.txt');
const b = await readFileP('b.txt');
const c = await readFileP('c.txt');
console.log(a+b+c);
}