TIL. 72 콜백 함수(Callback)의 정확한 의미

조윤식·2022년 9월 15일
0

StackOverflow의 한 이용자의 답변을 인용하겠다.

A callback function is a function which is:

passed as an argument to another function, and,
is invoked after some kind of event.

간단명료한 답변이다.

- 즉, 콜백 함수란

  1. 다른 함수의 인자로써 이용되는 함수.
  2. 어떤 이벤트에 의해 호출되어지는 함수.
// The callback method
function meaningOfLife() {
    log("The meaning of life is: 42");
}


// A method which accepts a callback method as an argument
// takes a function reference to be executed when printANumber completes
function printANumber(int number, function callbackFunction) {
    print("The number you provided is: " + number);
}

// Driver method
function event() {
   printANumber(6, meaningOfLife);
}
//hello!
function printHello(){
 print('hello');
}
//bye!
function printBye(){
  print('bye');
}

//특정 함수를 매개변수로 받아서 3초 뒤에 실행하는 함수
function sleepAndExecute(sleepTimeSecond, callback){
  //sleepTimeSecond 초 만큼 대기
  sleep(sleepTimeSecond);
  //전달된 callback 실행
  callback();
}

//3초 뒤에 hello 출력하기
sleepAndExecute(3, printHello);

//5초 뒤에 bye 출력하기
sleepAndExecute(5, printBye);

슈도 코드를 별로 좋아하는 편은 아니지만... 딱히 이해하기에 어렵지 않은 코드이기 때문에 그대로 인용하겠다.

printANumber()의 두 번째 매개변수로 function 타입의 callbackFunction을 인자로 받는다.

event()내부에서 printANumber(6, meaningOfLife); 를 하고 있는데,
meaningOfLife는 printANumber의 매개변수인 callbackFunction에 전달된다.

따라서 meaningOfLife는 위에서 밝힌 1번 정의(다른 함수의 인자로써 이용되는 함수)에 부합하여 callback 함수라고 할 수 있다

sleepAndExecute는 주어진 시간(초)만큼 대기했다가, callback 함수를 실행시키는 함수다.

이런식으로 작성하면, sleepAndExecute는
얼마나 대기할 것인지도 마음대로 정할 수 있고,
어떤 함수를 실행할 것인지도 마음대로 정할 수 있다.

callback함수의 첫 번째 정의인 "다른 함수의 인자로써 이용되는 함수"의 관점에서 바라보자.

sleepAndExecute(3, printHello); 에서는
printHello를 sleepAndExecute의 매개변수(인자)로 전달하므로,
printHello는 callback 함수라고 할 수 있다.

마찬가지로, sleepAndExecute(5, printBye)에서는
printBye를 sleepAndExecute의 매개변수(인자)로 전달하므로,
printBye는 callback 함수라고 할 수도 있다.

두 번째의 "어떤 이벤트에 의해 호출되어지는 함수"는 어떤 경우인가?

컴퓨터공학에서 이벤트는 "어떤 일이 발생했다"로 받아들여도 좋다.

즉, 스마트폰에서 화면을 누르는것도 이벤트고,
충전 케이블을 연결하는 것도 이벤트다.

충전 케이블을 연결하면 "케이블이 연결되었습니다"가 표시된다고 가정하고 슈도 코드를 보자.

function onCableConnected(){
	print("케이블이 연결되었습니다");
};

//케이블이 연결될 때 마다 전달된 onCableConnected가 호출된다고 가정
setOnCableConnected(onCableConnected);

setOnCableConnected로 설정한 함수가, 케이블을 연결할 때 마다 호출되므로,
onCableConnected는 "어떤 이벤트에 의해 호출되어지는 함수", 즉 callback 함수 라고 할 수 있다.

=============================================
답변의 마지막 문장에 좋은 문장이 있어서 덧붙이고 글을 마친다.

in other words "called at the back" of the other function.
다른 말로 바꿔 말해서, Callback은 called at the back 을 의미한다!

출처: https://satisfactoryplace.tistory.com/18 [만족:티스토리]

profile
Slow and steady wins the race

0개의 댓글