하루를 끝내며 다짐하기

HTTP 요청과 콜백함수란?(What is a Callback Function?) 본문

Weekly I learned

HTTP 요청과 콜백함수란?(What is a Callback Function?)

보슬비처럼 2023. 4. 13. 19:20
What is a Callback Function? 

       To create a callback function in JavaScript, one needs to pass it as a parameter to another function and invoke it after an event of task completion. Is it too complicated? Let's see how it works. 

자바스크립트에서 콜백 함수를 생성하려면, 해당 함수를 다른 함수의 매개변수로 전달하고 작업 완료 또는 이벤트 후에 호출해야 합니다. 이게 너무 복잡해 보이실 수 있을 거예요. 이제 이것이 어떻게 작동하는지 살펴보겠습니다.

setTimeout(function(){
       console.log("This message is shown after 3 seconds");
}, 3000);

       Let me provide a simple example to illustrate the concept of callback function in JavaScript. Suppose we want to display a message in the console after a delay of 3 seconds. To achieve this, we can define a function named "message" that logs the desired message to the console. Then we use the built-in method "setTimeout" to call the "message" function after a specified delay of 3 seconds. In this case, the "message" function is a callback function, which is invoked after the specified delay (i.e., after something has happened), and not before.

자바스크립트에서 콜백 함수의 개념을 이해하기 위해 간단한 예제가 있습니다. 우리가 3초의 딜레이 후 콘솔에 메시지를 표시하고자 할 때, "message"라는 함수를 정의하여 콘솔에 원하는 메시지를 기록하도록 합니다. 그리고 내장 메소드인 "setTimeout"을 사용하여 지정된 3초 후에 "message" 함수를 호출합니다. 이 경우 "message" 함수가 콜백 함수가 됩니다. 이는 지정수가 된 딜레이 후에 (즉, 어떤 일이 일어난 후에) 호출되며, 그 이전에는 호출되지 않도록 되어있습니다.

Arrow function in callback

      The setTimeout method in JavaScript is to use an arrow function, which is a newer type of function in ES6. In this case, we can define the callback function inline, right inside the setTimeout method, using the arrow function syntax. The arrow function takes no arguments, and its body consists of a single statement that logs the desired message to the console. Here's how we can write the callback function using an arrow function:

JavaScript에서 setTimeout 메소드를 사용하는 방법 중 하나는 ES6의 새로운 함수 유형인 화살표 함수를 사용하는 것입니다. 이 경우, 화살표 함수 구문을 사용하여 콜백 함수를 인라인으로 정의할 수 있습니다. 화살표 함수는 인수를 취하지 않은 상태로 몸통은 콘솔에 원하는 메시지를 기록하는 단일 문으로 구성될수 있습니다. 아래 화살표 함수를 구성하는 방법입니다:

setTimeout(() => console.log("This message is shown after 3 seconds"), 3000);

setTimeout(() => console.log("이 메세지는 3초 후에 나타납니다."), 3000);
 What is the event that happen in callback?

    In JavaScript, we can use callback functions for event declarations. For instance, we can create a button with an event that triggers a message to be displayed on the console when it is clicked. To achieve this, we first select the button element using its ID with the document.querySelector method. Then, we attach an event listener to the button using the addEventListener method, which takes two parameters. The first parameter is the event type, in this case, "click". The second parameter is a callback function that logs the desired message to the console when the button is clicked. Here's how we can write this using code:

JavaScript에서는 콜백 함수를 이벤트 선언에 사용할 수 있습니다. 예를 들어, 버튼을 만들어 클릭 시 콘솔에 메시지를 표시하는 이벤트를 만들수 있습니다. 이를 위해, document.querySelector 메소드를 사용하여 버튼 요소를 먼저 선택합니다. 그런 다음 addEventListener 메소드를 사용하여 버튼에 이벤트 리스너를 추가합니다. addEventListener 메소드는 두 개의 매개변수를 사용합니다. 첫 번째 매개변수는 이벤트 유형이며, 여기에서는 "click"입니다. 두 번째 매개변수는 버튼이 클릭되었을 때 콘솔에 표시되는 원하는 메시지를 기록하는 콜백 함수입니다. 이를 코드로 작성하는 방법은 다음과 같습니다:

document.querySelector("#callback-btn")
    .addEventListener("click", function() {    
      console.log("User has clicked on the button!");
});

document.querySelector("#callback-btn")
    .addEventListener("click", function() {    
      console.log("사용자가 버튼을 클릭하였습니다!");
});
HTTP 와 callback 함수는 어떻게 작용하는가?

Before we start, let's first understand what HTTP is.

시작하기 전에 먼저 HTTP가 무엇인지 알아봅시다.

 

According to w3school website, HTTP stands for Hypertext Transfer Protocol. It is an application layer protocol that is used for communication between web servers and clients.

HTTP는 Hypertext Transfer Protocol의 약자이며, 웹 서버와 클라이언트 간의 통신에 사용되는 응용 프로그램 계층 프로토콜입니다. HTTP는 데이터 통신의 기초이며, HTML 문서, 이미지, 비디오 및 기타 파일과 같은 다양한 유형의 데이터를 웹 서버와 클라이언트 간에 전송하는 데 사용됩니다.

 

In a fun project where I made HTTP requests one after another, I used a code that I didn't completely understand at the time. However, now that I have learned more about callback functions, I can finally see how the code works!

HTTP 요청은 비동기로 이루워지며 아래의 코드는 토이프로젝트 당시 적용 하였던 코드입니다. 

그 당시에는 사실 정확하게 내용을 이해하지 못했지만, 현재 콜백 함수의 대한 공부를 하고 나니 어떤 작용을 하는지 

읽을 수 있게 되었습니다.

<script>
        function login() {
            $.ajax({
                type: "POST",
                url: "/api/login",
                data: {
                    id_give: $('#input-id').val(),
                    pw_give: $('#input-password').val(),
                },
                success: function (response) {
                    console.log(response)
                    if (response['result'] == 'success') {
                        // 로그인에 성공하면 token을 쿠키에 저장함.
                        $.cookie('mytoken', response['token']);
                        alert('로그인 완료')
                        window.location.href = '/'
                    } else {
                        alert(response['msg'])
                    }
                }
            })
        }
    </script>

This code uses a callback function called "success" in an AJAX request. The function is executed when the request is successful. The function logs the response, checks if the login was successful, saves a token to a cookie, and redirects the user to the home page if the login was successful. If the login was not successful, it displays an error message. Callback functions help handle the response after the request has been sent, and allow for asynchronous execution of the request.

 

이 코드는  AJAX 요청 내에서 "success" 속성의 형태로 콜백 함수를 활용합니다. success 속성은 AJAX 요청이 성공할 때 실행될 콜백 함수를 값으로 사용합니다. 이 경우 콜백 함수는 콘솔에 응답을 기록하고 로그인 성공 여부를 확인하고 jQuery 쿠키 플러그인을 사용하여 쿠키에 토큰을 저장하고 로그인에 성공하면 사용자를 홈 페이지로 리디렉션합니다. 로그인에 실패하면 사용자에게 오류 메시지가 표시됩니다. 콜백 함수를 사용하면 AJAX 요청을 비동기식으로 실행할 수 있고 응답을 받은 후 처리할 수 있습니다.

 

HTML request methods include GET/POST/DELETE, etc., and are used as requests to create, execute, or receive resources, and are also used to remove specific resources.

HTML 의 요청 메소드에는 GET/POST/DELETE 등이 있으며 리소스를 생성하거나 실행 또는 받기위한 요청으로도 사용되며 특정 리소스를 제거하는 데에도 사용이 됩니다.

Other things about Callbacks

Callbacks are an essential concept in JavaScript programming because they enable asynchronous operations to be executed effectively. However, as the number of asynchronous operations grows, it can lead to a problem known as "callback hell", where the code becomes difficult to read and maintain. To solve this problem, developers often use Promises or Async/Await functions to simplify asynchronous code and avoid callback hell.

콜백은 비동기 작업을 효과적으로 실행할 수 있도록하는 JavaScript 프로그래밍에서 중요한 개념입니다. 그러나 비동기 작업의 수가 증가하면 할 수록  "콜백 지옥"이라는 문제가 발생하게되고, 코드가 읽기 어렵고 유지 보수하기 어려워지게 됩니다. 이 문제를 해결하기 위해 개발자들은 종종 Promises나 Async/Await 함수를 사용하여 비동기 코드를 간소화하고 콜백 지옥을 피한다고 합니다. 

 

At the end of retrospective analysis

As I began my journey into learning JavaScript, I quickly discovered that callbacks are a crucial aspect of Frontend.

In the near future, I anticipate crafting a comprehensive post on callbacks, delving into the intricate concept of callback hell and its potential solutions.

나는 JavaScript를 배우기 시작하면서 콜백이 지금 공부하는 부분에 중요한 측면임을 빠르게 알 수 있었고, 

가까운 미래에 콜백의 개념과 해결책을 더 자세하게 다룬 게시물을 올릴 수 있었으면 한다.

 

 

 

References

JavaScript Callback Functions – What are Callbacks in JS and How to Use Them:

https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/

 

What is HTTP?:

https://www.w3schools.com/whatis/whatis_http.asp

 

반응형
Comments