알 수 없는 사용자 2021. 6. 7. 20:26

Callback

다른 함수의 인자로 전달되는 함수를 뜻한다.

 

아래의 코드를 실행해보면 setTimeout이 비동기적 처리를 하기 때문에 새로 추가한 포스트가 getPost 메서드를 통해 표출되지 않는다.

const posts = [
  {
    title: "Post One",
    body: "This is post one"
  }, {
    title: "Post Two",
    body: "This is post Two"
  }
];

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

function getPost() {
  setTimeout(function (){
    let output = "";

    posts.forEach(function (post) {
      output += `<li>${post.title}</li>`;
    });

    document.body.innerHTML = output;
  }, 1000);
}

createPost({title: "Post Three", body: "Three"});
getPost();

 

 

이 때 Callback function을 이용하여 다음과 같이 포스트를 만들 때 새로 추가된 포스트까지 가져오는 기능을 구현할 수 있다.

 

...

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

...

createPost({title: "Post Three", body: "Three"}, getPost);