callback

차노·2023년 8월 3일
0

JS

목록 보기
17/96

JavaScript is an asynchronous language, which means that it can handle multiple tasks simultaneously.

자바스크립트는 비동기 언어이며, 다중 실행을 동시에 핸들링할 수 있다

What are callbacks?

A callback is a function that is passed as an argument to another function, and is called after the main function has finished its execution.

콜백은 다른 펑션에게 인자를 전달하는 펑션이며 메인 펑션이 실행을 완료하면 호출되는 함수이다.

The main function is called with a callback function as its argument, and when the main function is finished, it calls the callback function to provide a result.

메인 함수는 인자로서 콜백 펑션과 함께 호출되며, 메인 펑션이 완료되면 결과값을 제공하기 위해 콜백펑션을 호출한다

Callbacks allows you to handle the result of an asynchronous operation in a non-blocking manner, which means that the program can continue to run while the operation is being executed.

콜백은 논블로킹 방식에서 비동기 작업의 결과값을 핸들링하게끔 만들며, 이는 작업이 실행되고 이있는 와중에 계속해서 run할 수 있음을 의미한다. 즉 순서대로 차근차근 실행되는 것이 아니라 다중 실행을 의미하며 호출함수를 통해 서로 다른 함수를 부르며 값을 반환한다.

여기에서 non blocking의 의미는 다른 함수가 실행하고 있을 때 또 다른 함수의 실행을 막지 않고 비동기의 방식으로 실행하는 것을 의미한다.

Non-blocking
Callbacks allow for non-blocking programming, which means that the programs does not stop and wait for an operation to complete before continuing to execute.

Closure
A closure is a function that has access to variables in its outer scope, even after the outer function has returned.

클로져는 아우터 펑션이 반환후에도, 아우터 스콥에서 변수에 접근할 수 있는 함수이다

Explanation:

  • We first define a mainFunction that takes a callback as an argument.

    인자로 콜백을 받는 메인펑션을 정의한다.

  • The mainFunction uses setTimeout to simulate an asynchronous operation. The setTimeout function takes two arguments: a callback function and a delay time in millseconds.

    메인 함수는 비동기 작업을 위해 setTimeout을 simulate 한다. setTimeout 함수는 두 인자를 받는데, 콜백 함수와 dealy time을 받는다.

  • The setTimeout function calls the callback function with the result of the operation after the specified delay time.

    setTimeout 함수는 특정 delay time 지나고 나서 작업물의 결과와 함께 콜백함수를 호출한다.

  • We then define a callbackFunction that logs the result of the operation.

    _오퍼레이션의 결과에 로그하는 callbackFunction을 정의한다.

  • Finally, we call the mainFunction with the callbackFunction as its argument.

Reference

0개의 댓글