콜백지옥

Tags

예시를 위한 간단 클래스

class UserStorage { loginUser(id, password, onSuccess, onError) { setTimeout(() => { if ( (id === 'nightohl' && password === 'myworld') || (id === 'guest' && password === 'test') ) { onSuccess(id); } else { onError(new Error('not found')); } }, 2000); } getRoles(user, onSuccess, onError) { setTimeout(() => { if (user === 'nightohl') { onSuccess({ name: 'nightohl', 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(`Hi ${userWithRole.name}, you have a ${userWithRole.role} role`); }, error => { console.log(error); }, ); }, error => { console.log(error); }, );
  • 콜백에 콜백에..

단점

  • 가독성이 매우 떨어져 의미 파악도 힘들고
  • 실수를 할 확률이 높아진다.
  • 코드 수정하기도 어려워짐