
콜백 함수(callback function)는 다른 함수의 인수로 전달되어, 나중에 호출되는 함수
주로 비동기적인 작업을 처리하거나 이벤트 처리, 데이터 처리 등에 사용.
콜백 함수를 사용하면 비동기적인 작업이 완료된 후에 결과를 처리하거나 특정 이벤트가 발생했을 때 처리할 로직을 지정할 수 있음.
이를 통해 코드의 유연성과 재사용성을 높일 수 있음.
// 비동기적으로 데이터를 불러오는 함수
function fetchData(callback) {
// 시뮬레이션을 위해 setTimeout 사용
setTimeout(() => {
const data = "This is the fetched data";
// 콜백 함수 호출하여 데이터 전달
callback(data);
}, 2000); // 2초 후에 데이터를 전달
}
// fetchData 함수 호출
fetchData(function(data) {
console.log("Data received:", data); // 출력: Data received: This is the fetched data
});
이 예시에서 fetchData 함수는 비동기적으로 데이터를 불러오는 함수임.
이 함수는 콜백 함수를 인수로 받아서, 데이터를 가져오고 나중에 이 데이터를 전달함.
fetchData 함수가 데이터를 가져온 후에는 콜백 함수가 호출되고, 이때 데이터가 전달됨.
이를 통해 비동기적인 작업이 완료된 후에 결과를 처리할 수 있음.
콜백 지옥(callback hell)은 콜백 함수를 중첩하여 사용할 때 코드가 복잡하고 가독성이 떨어지는 상황
asyncFunction1(function(result1) {
asyncFunction2(result1, function(result2) {
asyncFunction3(result2, function(result3) {
asyncFunction4(result3, function(result4) {
// 계속해서 콜백 함수를 중첩하여 사용
});
});
});
});
asyncFunction1()
.then(result1 => asyncFunction2(result1))
.then(result2 => asyncFunction3(result2))
.then(result3 => asyncFunction4(result3))
.then(result4 => {
// Promise 체인을 통해 코드를 간결하게 작성
})
.catch(error => {
// 에러 처리
console.error("An error occurred:", error);
});
async function fetchData() {
try {
const result1 = await asyncFunction1();
const result2 = await asyncFunction2(result1);
const result3 = await asyncFunction3(result2);
const result4 = await asyncFunction4(result3);
// 비동기 작업이 완료된 후에 이어지는 로직
} catch (error) {
// 에러 처리
console.error("An error occurred:", error);
}
}