종우의 컴퓨터 공간

Callback Functions 본문

자바 스크립트 (JavaScript)/Asynchronous JS, Ajax & Fetch API

Callback Functions

종우공간 2021. 8. 11. 02:20

Callback Function이란?

- argument로 다른 함수에게 전달되는 함수를 의미한다.

- function that can be passed into another function and then called within that function

- 자바스크립트에서 함수는 Object이다. 이 때문에 함수는 다른 함수의 인자로 쓰일 수도, 어떤 함수에 의해 리턴될 수도 있다. 이러한 함수를 고차함수(higher-order function)이라 부르고 인자로 넘겨지는 함수를 콜백함수(call-back-function)이라고 부른다.

Callback Function이 필요한 이유?

- 자바스크립트는 이벤트 기반 언어이기 때문이다. 자바스크립트는 다음 명령어를 실행하기 전 이전 명령어의 응답을 기다리기 보단, 다른 이벤트들을 기다리며 계속 명령을 수행한다. 따라서 이벤트가 진행되는 순서에 있어서 꼬일 수가 있는데 그것을 방지하기위해 콜백 함수를 사용한다.

- 아래 예제에서는, 포스트를 먼저 만들고나서 그다음에 포스트들을 가져오는 식으로 진행했지만 포스트를 만드는데 걸리는 시간이 좀 더 길기 떄문에 방금 만들어진 포스트는 가져오지 못하는 상황이 발생하였다. 따라서 포스트를 만드는 함수 안에 인자로써 포스트를 가져오는 함수를 콜백함수로 받아와서 그 안에서 불려지게끔 코드를 작성하였다.

예제

const posts = [
  {
    title: 'Post one',
    body: 'This is post one'
  },
  {
    title: 'Post two',
    body: 'This is post two'
  }
];

// synchronous way
function createPost(post) {
  setTimeout(function() {
    posts.push(post);
  }, 2000);
}

function getPosts() {
  setTimeout(function() {
    let output = '';
    posts.forEach(function(post) {
      output += `<li>${post.title}</li>`;
    });
    document.body.innerHTML = output;
  }, 1000);
}

createPost({title: 'Post three', body: 'This is the post three'});
getPosts();

// asynchronous way(callback way)
function createPost(post, callback) {
  setTimeout(function() {
    posts.push(post);
    callback();
  }, 2000);
}

function getPosts() {
  setTimeout(function() {
    let output = '';
    posts.forEach(function(post) {
      output += `<li>${post.title}</li>`;
    });
    document.body.innerHTML = output;
  }, 1000);
}

createPost({title: 'Post three', body: 'This is the post three'}, getPosts);