자바스크립트에서 콜백 함수가 전달된 함수에게 제어권이 이양된다는 것은,
콜백 함수의 실행을, 전달받은 함수가 결정한다는 의미이다.
즉, 콜백 함수는 호출 시점과 실행 순서를 전달받은 함수의 논리에 따라 결정된다.
이는 비동기 작업에서 특히 중요하다.
1. 즉시 실행되는 경우
콜백 함수는 전달받은 함수가 호출하는 즉시 실행된다.
🖥️ javascript
function executeImmediately(callback) {
console.log("Before calling the callback");
callback(); // 제어권 이양
console.log("After calling the callback");
}
executeImmediately(function () {
console.log("I am the callback!");
});
🖥️ 출력:
mathematica
Before calling the callback
I am the callback!
After calling the callback
2. 조건에 따라 실행되는 경우
전달받은 함수는 특정 조건이 충족될 때만 콜백을 호출한다.
🖥️ javascript
function executeOnCondition(condition, callback) {
if (condition) {
console.log("Condition met, executing callback...");
callback(); // 제어권 이양
} else {
console.log("Condition not met, no callback execution.");
}
}
executeOnCondition(true, function () {
console.log("Callback executed!");
});
executeOnCondition(false, function () {
console.log("You won't see this.");
});
🖥️ 출력 :
mathematica
Condition met, executing callback...
Callback executed!
Condition not met, no callback execution.
3. 비동기 작업 완료 후 실행
콜백 함수는 비동기 작업이 완료되었을 때 실행된다.
🖥️ javascript
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
console.log("Data fetched!");
callback(); // 제어권 이양
}, 2000);
}
fetchData(function () {
console.log("Callback executed after data fetching.");
});
🖥️ 출력 :
kotlin
Fetching data...
Data fetched!
Callback executed after data fetching.
4. 이벤트 처리에서의 제어권 이양
이벤트가 발생했을 때 콜백이 호출된다.
🖥️ javascript
document.addEventListener("click", function () {
console.log("Callback executed on click event.");
});
위 예제에서 클릭 이벤트가 발생할 때 브라우저가 콜백 함수 호출을 담당한다.
🖥️ javascript
function mainFunction(callback) {
console.log("Main function starts.");
callback(); // 여기서 제어권 이양
console.log("Main function ends.");
}
mainFunction(function () {
console.log("I am the callback function.");
});
🖥️ 출력 :
bash
Main function starts.
I am the callback function.
Main function ends.
콜백 함수의 호출 시점은, 항상 콜백을 수신한 함수에 의해 결정된다는 점을 기억하면 된다!😊