9. Callback 지옥

김혜지·2021년 4월 24일

1. 동기와 비동기

  • Javascript는 synchronous이다
  • hoisting이 된 이후부터 코드가 순서에 맞춰 동기적으로 실행됨
  • hoisting: var, function 선언 들이 코드 맨 위로 자동으로 올라가는 것
console.log(`1`);
setTimeout(() => console.log(`2`), 1000);
console.log(`3`);    
//1 3 2 
// Synchronous callback
function printImmediately(print) {
  print();
}
printImmediately(() => console.log(`hello`));   // 1 3 hello 2
// Asynchronous callback
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log(`async callback`), 2000);  
// 1 3 hello 2 async callback

2.콜백지옥 체험

class UserStorage {
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === `ellie` && password === `1234`) ||
        (id === `hyeji` && password === `0233`)
      ) {
        onSuccess(id);
      } else {
        onError(new Error(`not found`));
      }
    }, 2000);
  }
  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === `ellie`) {
        onSuccess({ name: `ellie`, role: `admin` });
      } else {
        onError(new Error(`no access`));
      }
    }, 1000);
  }
}
const userStorage = new UserStorage();
const id = prompt(`enter your id`);
const password = prompt(`enter your password`);
userStorage.loginUser(
  id,
  password,
  user => {
    userStorage.getRoles(
      user,
      userwithRole => {
        alert(`hello ${userwithRole.name}, you have a ${userwithRole.role}role`);
      },
      error => {
        console.log(error);
      }
    );
  },
  error => {
    console.log(error);
  }
);

3. 콜백 체인의 문제점

  • 가독성이 떨어진다
  • 비즈니스 로직을 이해하기 힘들다
  • 디버깅 할 때 어렵다
  • 유지보수 어렵다

0개의 댓글