FrontEnd/JS

콜백 함수란?

행복한 기린님 2023. 1. 20. 16:17

알고 있다고 생각하는 개념도 설명하라고 하거나 정의를 물어보면 명확하게 얘기하지 못하는 경우가 많다.

그래서 이번 기회에 정리하여 머리 깊게 개념을 넣고자 한다.

 

콜백 함수란?

Callback function

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

해석하자면,

콜백함수는 다른 함수에 argument(인수)로 전달되는 함수이다, 외부함수의 내부에서 invoked(호출)되어 어떤 종류의 루틴이나 동작을 완료한다.

 

 

함수 인수로 함수가 전달되어 외부함수의 내부에서 호출되어 동작을 하는 함수!

말이 상당히 헷갈린다. 그래서 매번 뭐였지 하고 생각하나보다.

 

함수를 인수로 넘길 수 있다는 점이 신기할 수 있는데, 

자바스크립트에서는 함수를 Object로 보고 그렇기에 인수로 넣을 수도, 함수의 return 값으로도 사용할 수 있다.

 

 

아래는 MDN이 제공하는 예시 코드이다.

function greeting(name) {
  alert(`Hello, ${name}`);
}

function processUserInput(callback) {
  const name = prompt("Please enter your name.");
  callback(name);
}

processUserInput(greeting);

 

processUserInput이 실행되면서 이름을 입력받는 창이 나타나고 입력을 하면 입력한 값이 greeting 함수 인수로 넘어가면서 

alert('Hello, 입력한이름') 이 된다.

 

콜백함수의 형태는 위와 같다.

 

이제 가장 중요한 부분

왜 쓰는가?

 

Callbacks are generally used when the function needs to perform events before the callback is executed, or when the function does not (or cannot) have meaningful return values to act on, as is the case for Asynchronous JavaScript (based on timers) or XMLHttpRequest requests. Useful examples can be found in JavaScript libraries such as jQuery where the .each() method iterates over an array-like object, the first argument being a callback that is performed on each iteration.

콜백은 일반적으로 함수가 콜백을 실행하기 전에 이벤트를 실행해야 할 때, 또는 비동기 자바스크립트나 XMLHttpRequest 요청처럼 함수가 의미있는 값을 반환하지 않을  때 사용한다. 사용할만 예는 jQuery와 같은 라이브러리의 .each() 메소드에서 배열과 같은 객체에 대해 반복할 때, 첫 번째 인수는 매번 실행되는 콜백이다.

 

위키에서 가져온 글이라 이해하기 어렵다. 설명을 조금 더 보자

Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as fetch().

그러나 콜백은 비동기 작업이 완료된 후에도 코드 실행을 계속하기 위해 사용되는 경우가 많은데, 이를 비동기 콜백이라고 합니다. 좋은 예는 약속이 이행되거나 거부된 후 약속의 끝에 체인으로 연결된 .then() 블록 내에서 실행되는 콜백 함수이다. 이 구조는 fetch()와 같은 많은 현대 웹 API에 사용된다.

 

쉽게 얘기하면 

1. A함수 실행 전 B이벤트를 실행해야하는 경우

2. 비동기JS 문법(Timeout)또는 비동기 통신(XMLHttpReqeust)(Ajax)과 같이 의미있는 값을 반환하지 않는 경우

3. jQuery의 .each() 문법에서 배열과 같은 객체에 대해 반복하는 경우

사용한다.

 

한가지 더 보자면

A함수에서 비동기 통신을 하고 B함수를 실행하기 위해 

A();

B(); 

라고 한다면 A 함수에서 비동기 통신이 끝나기 전에 B 함수를 실행하기에 문제가 될 수 있다.

 

그래서 

function A(callBack) {
	비동기 통신
	callBack()
}

function B() {
	비동기 통신 뒤 하고 싶은 동작
}

이러한 형태로 콜백함수를 활용한다.

비동기 통신 promise 에서는 .then()으로 활용하고 있다

 

하지만 이런 방법으로 콜백함수를 구현하고, 콜백 함수 속에 콜백 함수가 들어가고 그 속에 콜백함수가 들어가게되는

콜백 지옥에 갇힐 수 있다.

step1(function (value1) {
    step2(function (value2) {
        step3(function (value3) {
            step4(function (value4) {
                step5(function (value5) {
                    step6(function (value6) {
                        // Do something with value6
                    });
                });
            });
        });
    });
});

 

비동기 통신에서 콜백 지옥에 갇히지 않도록 async/await 문법을 제공하고있다.

콜백지옥에 갇히지 않도록 ES6에서는 비동기 통신 객체 Promise를 제공한다.

 

 

 

 

 

참조

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

 

Callback function - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

developer.mozilla.org

 

https://en.wikipedia.org/wiki/Callback_(computer_programming) 

 

Callback (computer programming) - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search A function provided as an argument to another function to be called during its execution A callback is often back on the level of the original caller. In computer programming, a callba

en.wikipedia.org

https://velog.io/@ko1586/Callback%ED%95%A8%EC%88%98%EB%9E%80-%EB%AD%94%EB%8D%B0

 

Callback함수란?? 뭔데??

아 진짜 짜증났다...넌 힘내라!! 커몬~~

velog.io