Callback
Callback
A function passed as an argument to another function and called later. The basis of asynchronous programming. Beware of callback hell.
Callback
A function passed as an argument to another function and called later. The basis of asynchronous programming. Beware of callback hell.
A callback is a function that is passed as an argument to another function and invoked at a specific point in time. The name comes from the idea of "call me back later," and it is widely used for event handling, handling the completion of asynchronous operations, and injecting user-defined behavior.
In JavaScript, callbacks are the foundation of asynchronous programming. When a time-consuming operation such as reading a file, making an HTTP request, or running a timer completes, the callback function is called. This pattern makes it possible to handle asynchronous operations without blocking the main thread.
The drawback of callbacks is that deep nesting leads to "Callback Hell." When multiple asynchronous operations must be processed sequentially, the code is indented into a pyramid shape and readability degrades sharply. Promise and async/await emerged to solve this problem.
The callback pattern also plays a key role in functional programming. Higher-order functions such as map, filter, and reduce take a callback and process each element of a collection. Event listeners, sort comparison functions, and middleware are all variations of the callback pattern as well.
// JavaScript 콜백 예제
// 1. 기본 콜백
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
greet('Alice', () => console.log('Callback executed!'));
// 2. 비동기 콜백 (타이머)
console.log('Start');
setTimeout(() => {
console.log('2초 후 실행');
}, 2000);
console.log('End');
// 3. 에러 우선 콜백 (Node.js 패턴)
function readFile(path, callback) {
// callback(error, data) 형태
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
callback(err, null);
return;
}
callback(null, data);
});
}
// 4. 콜백 지옥 예시 (안티패턴)
getUser(userId, (user) => {
getOrders(user.id, (orders) => {
getOrderDetails(orders[0].id, (details) => {
// 점점 깊어지는 중첩...
});
});
});
// 5. 배열 메서드와 콜백
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
Senior: This legacy code has callbacks nested five levels deep.
Junior: Should I refactor it with Promises?
Senior: Yes, if you change each callback into a function that returns a Promise and flatten it with async/await, it becomes much easier to read. util.promisify is useful too.
Interviewer: Please explain the difference between a callback and a Promise.
Candidate: A callback is a pattern of passing a function as an argument, while a Promise is an object that represents the result of an asynchronous operation. Promises can be chained, so they avoid callback hell, and errors can be handled collectively with catch.
Interviewer: What is an error-first callback?
Candidate: It is a Node.js convention in which the first argument of the callback is an error object. If there is no error, it is null; if there is one, it contains the error information. It is used in the form callback(err, result).
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: This callback is missing error handling. What happens if it fails?
Author: Oh, I only thought about the success case.
Reviewer: Follow the error-first pattern, or wrap it in a Promise and handle it with try-catch. If errors get swallowed, debugging becomes really difficult.